SlideShare une entreprise Scribd logo
1  sur  113
Télécharger pour lire hors ligne
Refactoring
Amir Barylko
(About me & how to find me)
Software Quality
Expert
Agile Coach
Architect
Developer
Cook
amir@barylko.com
@abarylko
http://bit.ly/abarylkop
Disappointment
Management
Your expectations
here...
There’s always lunch!
What is Refactoring?
Refactoring is a disciplined
technique for restructuring
an existing body of code,
altering its internal
structure without changing
its external behavior.
Martin Fowler
Refactoring, improving design of existing code
What happened?
Sharepoint?
Lack of time?
Lack of skill?
Poor management?
Text
Why Refactor?
Any fool can write code that
a computer can understand.
Good programmers write code
that humans can understand
Martin Fowler
Remove duplication
Remove duplication
Remove duplication
Make code
maintainable
Make code readable
(by humans)
Spaghetti Code
Technical Debt
Improve Design
Reduce BLOC
(beers x LOC)
When to Refactor?
Fixing bugs
Adding features
Code Review
Manager on Vacation?
100% sure the new
code is better
Cost Not to Refactor
greater than
Cost to Refactor
Cost = Doing the change
+ Testing it
+ Documentation
Risk of
Introducing bugs
Only refactor if you
are confident

(it works as before, no side effects)
Unit Tests
One class
One method
No dependencies
(mocks)
Hard to do
with Legacy Code
Core of TDD
Integration Tests
More than
one class
Communication
between
components
Acceptance tests
Black box testing
End to end
Given input
When doing YYY
Expect output
Works with
Legacy Code
Works with
New Code
Works with
-40!!!
Core of BDD
How to Refactor?
Code should be clear
Like telling a story
Refactoring
algorithm
Te
xt

M
et
ho

d?
Second
Write a test for it
Third
Make it better
Fourth
Run the tests
Repeat until
out of coffee
Nesting Conditionals
C#

public double SomeMethod()
{
var result = 0d;
if (_firstGuard)
{
result = FirstCalculation();
if (_secondGuard)
{
result = SecondCalculation();
}
}
return result;
}
C#

RE
public double BetterMethod()
{
if (!_firstGuard)
{
return 0;
}
if (!_secondGuard)
{
return FirstCalculation();
}
return SecondCalculation();
}

FAC
T

OR

ED
Ruby

class NestedCalculation
def awesome_method
first_calculation
||
second_calculation ||
default_calculation
end
def first_calculation
@first_guard && some_calc_here
end
def second_calculation
# etc...
end
end

RE

FAC
T

OR

ED
C#

public double SomeMethod()
{
var result = 0d;
if (_guard1)
{
if (_guard2)
{
if (_guard3)
{
result = Calc1() + Calc2();
}
}
}
return result;
}
C#

public double BetterMethod()
{
if (_guard1 && _guard2 && _guard3)
{
return Calc1() + Calc2();
}
return 0;
}

RE

FAC
T

OR

ED
C#

public bool SomeMethod()
{
var result = false;
if (_firstGuard)
{
if (_secondGuard)
result = true;
}
else
result = true;
return result;
}
C#

RE

public bool BetterMethod()
{
return !_firstGuard || _secondGuard;
}

FAC
T

OR

ED
Functional
Inspiration
DRY
Stop writing
custom loops
Meaning rulez
Java

public Iterable<String> deploy(
Iterable<String> collection) {
Collection<String> result = new ArrayList<>...;
Iterator<String> cursor = collection.iterator();
while(cursor.hasNext()) {
result.add("Deployed to " + cursor.next());
}
return result;
}
Java

public Iterable<String> betterDeploy(
Iterable<String> environments) {

RE

FAC
T

return with(environments)
.convert(new DeployConverter());
}
class DeployConverter
implements Converter<String, String> {
public String convert(String env) {
return "Deployed to " + env;
}
}

OR

ED
Java

public class Movie {
private String title;
private int review;
public Movie(String title, int review) {
this.title = title;
this.review = review;
}
public String getTitle() {...}
public int getReview() {...}
}
Java

@Test
public void whereAreMyPostIt() {
// arrange
Iterable<Movie> movies = asList(
new Movie("Blazing Saddles", 5), new Movie("Terminator"),
new Movie("Canadian Bacon", 8)
);
// act
Iterable<Movie> reviewed =
filter(having(on(Movie.class).getReview(), greaterThan(-1))
, movies);
// assert
assertThat(joinFrom(reviewed).getTitle(),
equalTo("Blazing Saddles, Canadian Bacon"));
}
Java

@Test
public void wheresMyGanttChart() {
// arrange
Iterable<Movie> movies = asList(new Movie("Blazing Saddles"),
new Movie("Terminator"), new Movie("Curator"));
// act
Matcher<Movie> endsWithAtor = new Predicate<Movie>() {
public boolean apply(Movie item) {
return item.getTitle().endsWith("ator");
}
};
Iterable<Movie> actual = filter(endsWithAtor, movies);
// assert
assertThat(joinFrom(actual).getTitle(),
equalTo("Terminator, Curator"));
}
C#

public int Mysterious(IEnumerable<int> collection)
{
return collection.Aggregate((a, b) => a + b);
}
Coffee

[1..1000].reduce (t, s) -> t + s
What about
MONADS?
Just kidding :)
Don’t forget OOP
Abstraction is
KEY
Coffee

class BudgetViewModel
constructor: (json) ->
@budgets
= [2013, 2012, 2011]
@budgetIndex = 0
salary: ->
return 5000 if @budgetIndex == 0
return 2000 if @budgetIndex == 1
1000
Coffee

RE
class BudgetViewModel
constructor: ->
@budgets = [
new BudgetModel(2013, 5000),
new BudgetModel(2012, 2000),
new BudgetModel(2011, 1000)
]
@budget = @budgets[0]
salary: => @budget.salary

FAC
T

OR

ED
Coffee
KO

class BudgetViewModel

RE

FAC
T

OR

constructor: ->
@budgets = ko.observableArray [
new BudgetModel(2013, 5000),
new BudgetModel(2012, 2000),
new BudgetModel(2011, 1000)
]
@budget = ko.observable()
@salary = ko.computed => @budget().salary

ED
Language is your friend
(or it should be)
The right tool
for the job
Coffee

class window.NewsViewModel
constructor: (@limit = -1) ->
@news = ko.observableArray()
@title = ko.observable()
$.getJSON '../api/news', @loadNews
loadNews: (data) =>
max = (if @limit == -1 then -1 else @limit - 1)
@news(@createNewsItem(e) for e in data[0..max])
@title @news()[0]?.Title
createNewsItem: (e) =>
newsItem =
Title: e.Title
Date: @parseDate(e.Date)
Body: e.Body
JS
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
window.NewsViewModel = (function() {
function NewsViewModel(limit) {
this.limit = limit != null ? limit : -1;
this.createNewsItem = __bind(this.createNewsItem, this);
this.loadNews = __bind(this.loadNews, this);
this.news = ko.observableArray();
this.title = ko.observable();
$.getJSON('../api/news', this.loadNews);
}
NewsViewModel.prototype.loadNews = function(data) {
var e, max, _ref;
max = (this.limit === -1 ? -1 : this.limit - 1);
this.news((function() {
var _i, _len, _ref, _results;
_ref = data.slice(0, max + 1 || 9e9);
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
e = _ref[_i];
_results.push(this.createNewsItem(e));
}
return _results;
}).call(this));
return this.title((_ref = this.news()[0]) != null ? _ref.Title : void 0);
};
NewsViewModel.prototype.createNewsItem = function(e) {
var newsItem;
return newsItem = {
Title: e.Title,
Date: this.parseDate(e.Date),
Body: e.Body
};
};
return NewsViewModel;
})();
}).call(this);
JVM supports
multiple languages
same for
.net framework
Testing is a great
place to start
Thank you!
amir@barylko.com
@abarylko
http://bit.ly/abarylkop
Books
Books
Photo Credit
•

Under http://creativecommons.org/licenses/by/2.5/

•
•

Bill Ward, Derek Schin's Trucks 1, http://flic.kr/p/m5L5S

•

Jeremy Keith, Roast beef, http://flic.kr/p/TKUz

•

Rob Campbell, Field of daisies, http://flic.kr/p/6QJjU4

•

•

Joe Cheng, DSC_7820-01, http://flic.kr/p/2Zt2u

Karin Dalziel, The Thinker, http://flic.kr/p/4UYArc

Under http://creativecommons.org/licenses/by-sa/3.0/us/

•

Derick Bailey, SOLID Motivational Posters, http://bit.ly/17aVaHg
Photo Credit 2
•
•

How to write good code, http://xkcd.com/844/
Understanding flow charts, http://lifehacker.com/5909501/how-tochoose-the-best-chart-for-your-data
Resources
•
•

http://www.infoq.com/news/2010/06/decision-to-refactor

•
•
•

Refactoring Catalog: http://www.refactoring.com/catalog/

http://stackoverflow.com/questions/38635/what-static-analysis-toolsare-available-for-c

LambdaJ: https://code.google.com/p/lambda
Coffeescript: http://coffeescript.org/

Contenu connexe

Tendances

Tendances (20)

Two Trains and Other Refactoring Analogies
Two Trains and Other Refactoring AnalogiesTwo Trains and Other Refactoring Analogies
Two Trains and Other Refactoring Analogies
 
Factory Girl
Factory GirlFactory Girl
Factory Girl
 
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
 
Day 5
Day 5Day 5
Day 5
 
Automated Refactoring With IntelliJ IDEA
Automated Refactoring With IntelliJ IDEA Automated Refactoring With IntelliJ IDEA
Automated Refactoring With IntelliJ IDEA
 
Forms in AngularJS
Forms in AngularJSForms in AngularJS
Forms in AngularJS
 
How to Create a l10n Payroll Structure
How to Create a l10n Payroll StructureHow to Create a l10n Payroll Structure
How to Create a l10n Payroll Structure
 
SQl
SQlSQl
SQl
 
Eric Lafortune - ProGuard and DexGuard for optimization and protection
Eric Lafortune - ProGuard and DexGuard for optimization and protectionEric Lafortune - ProGuard and DexGuard for optimization and protection
Eric Lafortune - ProGuard and DexGuard for optimization and protection
 
PHPSpec BDD Framework
PHPSpec BDD FrameworkPHPSpec BDD Framework
PHPSpec BDD Framework
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Symfony World - Symfony components and design patterns
Symfony World - Symfony components and design patternsSymfony World - Symfony components and design patterns
Symfony World - Symfony components and design patterns
 
Dutch php a short tale about state machine
Dutch php   a short tale about state machineDutch php   a short tale about state machine
Dutch php a short tale about state machine
 
ESWHO, ESWHAT, ESWOW -- FEDucation -- IBM Design
ESWHO, ESWHAT, ESWOW -- FEDucation -- IBM DesignESWHO, ESWHAT, ESWOW -- FEDucation -- IBM Design
ESWHO, ESWHAT, ESWOW -- FEDucation -- IBM Design
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to Production
 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in Scala
 
Rspec 101
Rspec 101Rspec 101
Rspec 101
 
Building a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesBuilding a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing Strategies
 
Patterns in PHP
Patterns in PHPPatterns in PHP
Patterns in PHP
 

Similaire à Refactoring

Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Victor Rentea
 
...and thus your forms automagically disappeared
...and thus your forms automagically disappeared...and thus your forms automagically disappeared
...and thus your forms automagically disappeared
Luc Bors
 

Similaire à Refactoring (20)

From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Rspec
RspecRspec
Rspec
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 
SCALA - Functional domain
SCALA -  Functional domainSCALA -  Functional domain
SCALA - Functional domain
 
Clean Code
Clean CodeClean Code
Clean Code
 
From clever code to better code
From clever code to better codeFrom clever code to better code
From clever code to better code
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
React/Redux
React/ReduxReact/Redux
React/Redux
 
Code Quality Practice and Tools
Code Quality Practice and ToolsCode Quality Practice and Tools
Code Quality Practice and Tools
 
Zend Certification PHP 5 Sample Questions
Zend Certification PHP 5 Sample QuestionsZend Certification PHP 5 Sample Questions
Zend Certification PHP 5 Sample Questions
 
Well
WellWell
Well
 
mobl
moblmobl
mobl
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Quick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using JasmineQuick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using Jasmine
 
Architecture refactoring - accelerating business success
Architecture refactoring - accelerating business successArchitecture refactoring - accelerating business success
Architecture refactoring - accelerating business success
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
...and thus your forms automagically disappeared
...and thus your forms automagically disappeared...and thus your forms automagically disappeared
...and thus your forms automagically disappeared
 

Plus de Amir Barylko

Beutiful javascript with coffeescript
Beutiful javascript with coffeescriptBeutiful javascript with coffeescript
Beutiful javascript with coffeescript
Amir Barylko
 
Rich UI with Knockout.js &amp; Coffeescript
Rich UI with Knockout.js &amp; CoffeescriptRich UI with Knockout.js &amp; Coffeescript
Rich UI with Knockout.js &amp; Coffeescript
Amir Barylko
 

Plus de Amir Barylko (20)

Functional converter project
Functional converter projectFunctional converter project
Functional converter project
 
Elm: delightful web development
Elm: delightful web developmentElm: delightful web development
Elm: delightful web development
 
Dot Net Core
Dot Net CoreDot Net Core
Dot Net Core
 
No estimates
No estimatesNo estimates
No estimates
 
User stories deep dive
User stories deep diveUser stories deep dive
User stories deep dive
 
Coderetreat hosting training
Coderetreat hosting trainingCoderetreat hosting training
Coderetreat hosting training
 
There's no charge for (functional) awesomeness
There's no charge for (functional) awesomenessThere's no charge for (functional) awesomeness
There's no charge for (functional) awesomeness
 
What's new in c# 6
What's new in c# 6What's new in c# 6
What's new in c# 6
 
Productive teams
Productive teamsProductive teams
Productive teams
 
Who killed object oriented design?
Who killed object oriented design?Who killed object oriented design?
Who killed object oriented design?
 
From coach to owner - What I learned from the other side
From coach to owner - What I learned from the other sideFrom coach to owner - What I learned from the other side
From coach to owner - What I learned from the other side
 
Communication is the Key to Teamwork and productivity
Communication is the Key to Teamwork and productivityCommunication is the Key to Teamwork and productivity
Communication is the Key to Teamwork and productivity
 
Acceptance Test Driven Development
Acceptance Test Driven DevelopmentAcceptance Test Driven Development
Acceptance Test Driven Development
 
Agile requirements
Agile requirementsAgile requirements
Agile requirements
 
Agile teams and responsibilities
Agile teams and responsibilitiesAgile teams and responsibilities
Agile teams and responsibilities
 
Beutiful javascript with coffeescript
Beutiful javascript with coffeescriptBeutiful javascript with coffeescript
Beutiful javascript with coffeescript
 
Sass & bootstrap
Sass & bootstrapSass & bootstrap
Sass & bootstrap
 
Rich UI with Knockout.js &amp; Coffeescript
Rich UI with Knockout.js &amp; CoffeescriptRich UI with Knockout.js &amp; Coffeescript
Rich UI with Knockout.js &amp; Coffeescript
 
Agile requirements
Agile requirementsAgile requirements
Agile requirements
 
SDEC12 Beautiful javascript with coffeescript
SDEC12 Beautiful javascript with coffeescriptSDEC12 Beautiful javascript with coffeescript
SDEC12 Beautiful javascript with coffeescript
 

Dernier

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

Refactoring