SlideShare uma empresa Scribd logo
1 de 28
Baixar para ler offline
Refactoring
Improving the design of existing code …
…. without changing the behavior!

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Why do good developers write bad software?
• Project and budget pressure lead to taking shortcuts
• You realize there are better ways to do something
• Requirements change over time
!

• When it’s hard to change update your code this lead to less optimal design

e fix our
w
How do
?
oftware
s

agile42 | The Agile Coaching Company

How do w

e know ou
r
software
is “bad”
… when it
works fin
e!

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Software development is not a Jenga game
• Single Responsibility Principle
• Just because you can, doesn’t mean you should.

• Open Closed Principle
• Open chest surgery is not needed when putting on a coat.

• Liskov Substitution Principle
• If it looks like a duck, quacks like a duck,

but needs batteries – you probably have the wrong abstraction

• Interface Segregation Principle
• You want me to plug this in, where?

• Dependency Inversion Principle
• Would you solder a lamp directly to the electrical wiring in a wall?

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Single Responsibility Principle
• A responsibility can be defined as a reason to change
!
!
!
!
!
!
!

• Just because you can, doesn’t mean you should.

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Open Closed Principle
• open for extension, but closed for modification
!
!
!
!
!
!
!

• Open chest surgery is not needed when putting on a coat.

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Liskov Substitution Principle
• use a subtype without changing the correctness of the program
!
!
!
!
!
!
!

• If it looks like a duck, quacks like a duck,

but needs batteries – you probably have the wrong abstraction
agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Interface Segregation Principle
• states that no client should be forced to depend on methods it does not use
!
!
!
!
!
!
!

• You want me to plug this in, where?

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Dependency Inversion Principle
• no dependencies on implementations only on abstractions
!
!
!
!
!
!
!

• Would you solder a lamp directly to the electrical wiring in a wall?

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Dependency Inversion Example
class EventLogWriter
{
public void Write(string message)
{
//Write to event log here
}
}

!

class AppPoolWatcher
{
// Handle to EventLog writer to write to the logs
EventLogWriter writer = null;

!

// This function will be called when the app pool has problem
public void Notify(string message)
{
if (writer == null)
{
writer = new EventLogWriter();
}
writer.Write(message);
}
}
agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Dependency Inversion Example

EventLogWriter
AppPoolWatcher
// This can be
watcher.Action

!

writer = new EventLogWriter();
watcher = new AppPoolWatcher();
done in some class
= writer;

// This can be done in some other class
watcher.Notify("Sample message to log");

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Dependency Inversion Example
class AppPoolWatcher
{
// Handle to EventLog writer to write to the logs
INofificationAction action = null;

!

!

public INofificationAction Action
{
get
{
return action;
}
set
{
action = value;
}
}
// This function will be called when the app pool has problem
public void Notify(string message)
{
action.ActOnNotification(message);
}

}
agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Refactoring
Improving the design of existing code
Without changing the behavior

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Refactoring
Released in 2000, already a
golden oldie, a book I recommend
everyone to read.
!
The book defines the technique
of refactoring and is a reference
for refactoring types.

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Code Smells
Refactoring Cheat Codes

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Code Smells
• The term code smells was introduced by Kent Beck, based on an important
lesson he learned from his Grandmother about children and diapers.



„If it stinks, change it”—Grandma Beck

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Code Smells
• Duplicated Code

• Primitive Obsession

• Inappropriate Intimacy

• Long Method

• Switch Statements

• Large Class

• Parallel Inheritance
Hierarchies

• Alternative Classes with
Different Interfaces

• Long Parameter List
• Divergent Change
• Shotgun Surgery
• Feature Envy
• Data Clumps

agile42 | The Agile Coaching Company

• Incomplete Library Class

• Lazy Class

• Data Class

• Speculative Generality

• Refused Bequest

• Temporary Field

• Comments

• Middle Man

• Dead Code

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Comments and Naming
• Comments

• Rename Method

• Add comments only to explain purpose

• Extract Method

• If comments need to explain how code work, it
smells.

!

• Instead use meaningful names, e.g.:

schedule.add(Course course)

!
!

!

!

!

!

• Type Embedded in Name

• Rename Method

• Uncommunicative Name
• Inconsistent Names

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Excess and Duplication
• Excess
• Long Method
• Long Parameter List
• Large Class
• Long methods, large classes and endless
parameters make code unreadable.
!

• Duplicated Code

• Extract Method
• Replace Temp with Query
• Introduce Parameter Object
• Extract Class
• Extract Subclass

!
!
!
• Replace Parameter with Method
• Pull Up Field
• Form Template Method
• Substitute Algorithm

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
The Past and the Future
• Dead Code

• Delete Code

• or worse, commented code

!

• Delete it, we have version control for that!

!

!
!

• Speculative Generality

• Collapse Hierarchy

• Don't attempt to predict future needs with
unnecessary generalization.

• Inline Class
• Remove Parameter
• Rename Method

YAGNI!

agile42 | The Agile Coaching Company

KISS

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Rename Method
// this method will return the maximum

void getMaximumCreditLimit() {

// credit limit.

return maximumCreditLimit;

void getIt() {

}

return _mCL;

void getInvoiceCreditLimit() {

}

int maximumCredit;

void getivcdlmt() {

float usedCredit;

int m;
float u;

=>

. .
}

. .
}

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Extract Method
void printOwing(double amount) {

void printOwing(double amount) {

printBanner();

printBanner();
printDetails(amount);

//print details

}

System.out.println ("name:" + _name);
System.out.println ("amount" + amount);
}

void printDetails (double amount) {

=>

System.out.println ("name:" + _name);
System.out.println ("amount" + amount);
}

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Replace Temp With Query
double basePrice = _quantity * _itemPrice;

if (basePrice() > 1000)

if (basePrice > 1000)

return basePrice() * 0.95;

return basePrice * 0.95;

else

else

return basePrice() * 0.98;

return basePrice * 0.98;

…
double basePrice() {

=>

return _quantity * _itemPrice;
}

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Introduce Parameter Object
double invoicedAmount(Date start, Date end) {

double invoicedAmount(Period range) {

double result;

double result;

for (Invoice invoice: invoices) {

for (Invoice invoice: invoices) {
if (range.contains(invoice.getDate()) {

if (invoice.getDate().after(start) ||

result += invoice.getAmount();

invoice.getDate().before(end)) {
}

result += invoice.getAmount();
}

}

return result;

}
return result;
}

=> !

}

class Period (Date start, Date end) {
. . .
boolean contains(Date date) {
return date.after(start) || date.before(end);
}
}

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Extract Class
class Person...
public String getName() {

class Person...
public String getName() {

return _name;
}
public String getTelephoneNumber() {
return ("(" + _officeAreaCode + ")"
+ _officeNumber);
}
String getOfficeAreaCode() {
return _officeAreaCode;
}
String getOfficeNumber() {
return _officeNumber;
}
private String _name;
private String _officeAreaCode;
private String _officeNumber;

agile42 | The Agile Coaching Company

return _name;

=> !

}
public String getTelephoneNumber(){
return _officeTelephone.getTelephoneNumber();
}
TelephoneNumber getOfficeTelephone() {
return _officeTelephone;
}
private String _name;
private TelephoneNumber _officeTelephone =
new TelephoneNumber();
class TelephoneNumber...
public String getTelephoneNumber() {
return ("(" + _areaCode + ") " + _number);
}
String getAreaCode() {
return _areaCode;
String getNumber() {
return _number;
}
private String _number;
private String _areaCode;

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Extract Subclass
class JobItem ...
public JobItem (int unitPrice,

class JobItem ...
public JobItem (int unitPrice) {

boolean isLabor,
Employee employee) {
_unitPrice = unitPrice;
_isLabor = isLabor;
_employee = employee;

!

}
public int getUnitPrice(){
return (_isLabor) ?
_employee.getRate():
_unitPrice;
}
...
class Employee...
public Employee (int rate) {
_rate = rate;
}
public int getRate() {
return _rate;
}
private int _rate;

_unitPrice = unitPrice;

!

=>

}
public int getUnitPrice(){
return _unitPrice;
}
...

class LaborItem ...
public LaborItem (Employee employee) {
super(0);
_employee = employee;
}
public int getUnitPrice(){
return_employee.getRate():
}
...

!

class Employee...
public Employee (int rate) {
_rate = rate;
}
public int getRate() {
return _rate;
}
private int _rate;

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Replace Parameter with Method
public double getPrice() {
int basePrice = _quantity * _itemPrice;
int discountLevel;
if (_quantity > 100) discountLevel = 2;
else discountLevel = 1;
double finalPrice =
discountedPrice (basePrice,discountLevel);
return finalPrice;
}

!

private double discountedPrice
(int basePrice, int discountLevel) {
if (discountLevel == 2)
return basePrice * 0.1;
else
return basePrice * 0.05;
}

agile42 | The Agile Coaching Company

public double getPrice() {
if (getDiscountLevel() == 2)
return getBasePrice() * 0.1;
else
return getBasePrice() * 0.05;
}

!

=>

private double getBasePrice() {
return _quantity * _itemPrice;
}

!

private int getDiscountLevel() {
if (_quantity > 100) return 2;
else return 1;
}

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
Substitute Algorithm
String foundPerson(String[] people){
for (int i = 0; i < people.length; i++) {
if (people[i].equals ("Don")){
return "Don";
}
if (people[i].equals ("John")){
return "John";
}
if (people[i].equals ("Kent")){
return "Kent";
}
}
return "";
}

=>
String foundPerson(String[] people){
List candidates = Arrays.asList(new String[] {"Don", "John", "Kent"});
for (int i=0; i &lt; people.length; i++)
if (candidates.contains(people[i]))
return people[i];
return "";
}

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.
References
• SOLID:


http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)
!
• SmellsToRefactorings:

http://users.csc.calpoly.edu/~jdalbey/305/Lectures/SmellsToRefactorings
!
• Martin Fowler refactoring site: http://refactoring.com/
!
• Dependency Injection: http://martinfowler.com/articles/injection.html

agile42 | The Agile Coaching Company

www.agile42.com |

All rights reserved. Copyright © 2007 - 2014.

Mais conteúdo relacionado

Mais procurados

Crafting ColdFusion Applications like an Architect
Crafting ColdFusion Applications like an ArchitectCrafting ColdFusion Applications like an Architect
Crafting ColdFusion Applications like an ArchitectColdFusionConference
 
How to get everything right... by doing everything wrong? (Andrea Tomasini, a...
How to get everything right... by doing everything wrong? (Andrea Tomasini, a...How to get everything right... by doing everything wrong? (Andrea Tomasini, a...
How to get everything right... by doing everything wrong? (Andrea Tomasini, a...Andrea Tomasini
 
Subconsultas
SubconsultasSubconsultas
SubconsultasMaria
 
Commonly used design patterns
Commonly used design patternsCommonly used design patterns
Commonly used design patternsMojammel Haque
 
Thoughts on Component Resuse
Thoughts on Component ResuseThoughts on Component Resuse
Thoughts on Component ResuseJustin Edelson
 
Introduction to React Native Workshop
Introduction to React Native WorkshopIntroduction to React Native Workshop
Introduction to React Native WorkshopIgnacio Martín
 

Mais procurados (6)

Crafting ColdFusion Applications like an Architect
Crafting ColdFusion Applications like an ArchitectCrafting ColdFusion Applications like an Architect
Crafting ColdFusion Applications like an Architect
 
How to get everything right... by doing everything wrong? (Andrea Tomasini, a...
How to get everything right... by doing everything wrong? (Andrea Tomasini, a...How to get everything right... by doing everything wrong? (Andrea Tomasini, a...
How to get everything right... by doing everything wrong? (Andrea Tomasini, a...
 
Subconsultas
SubconsultasSubconsultas
Subconsultas
 
Commonly used design patterns
Commonly used design patternsCommonly used design patterns
Commonly used design patterns
 
Thoughts on Component Resuse
Thoughts on Component ResuseThoughts on Component Resuse
Thoughts on Component Resuse
 
Introduction to React Native Workshop
Introduction to React Native WorkshopIntroduction to React Native Workshop
Introduction to React Native Workshop
 

Destaque

Riding the Agile Wave
Riding the Agile WaveRiding the Agile Wave
Riding the Agile WaveNUS-ISS
 
Workshop empowering teams
Workshop empowering teamsWorkshop empowering teams
Workshop empowering teamsNiels Verdonk
 
Be curious without judging - building a coaching structure
Be curious without judging  - building a coaching structureBe curious without judging  - building a coaching structure
Be curious without judging - building a coaching structureNiels Verdonk
 
Refactoring Techniques
Refactoring TechniquesRefactoring Techniques
Refactoring TechniquesMayada Ghanem
 
The Value of Refactoring on an Agile Team
The Value of Refactoring on an Agile TeamThe Value of Refactoring on an Agile Team
The Value of Refactoring on an Agile TeamRob Myers
 
Scrum Roles : Scrum Master | Product Owner |Team
Scrum Roles : Scrum Master | Product Owner |TeamScrum Roles : Scrum Master | Product Owner |Team
Scrum Roles : Scrum Master | Product Owner |TeamSaket Bansal
 
Room to Breathe: The BA's role in project estimation
Room to Breathe: The BA's role in project estimationRoom to Breathe: The BA's role in project estimation
Room to Breathe: The BA's role in project estimationufunctional
 
Product Owner Super Powers
Product Owner Super PowersProduct Owner Super Powers
Product Owner Super PowersStefan Haas
 
Agile Development Ultimate Slides
Agile Development Ultimate SlidesAgile Development Ultimate Slides
Agile Development Ultimate Slidesgilashikwa
 
Estimating and planning Agile projects
Estimating and planning Agile projectsEstimating and planning Agile projects
Estimating and planning Agile projectsMurray Robinson
 
The Role of a BA on a Scrum Team IIBA Presentation 2010
The Role of a BA on a Scrum Team IIBA Presentation 2010The Role of a BA on a Scrum Team IIBA Presentation 2010
The Role of a BA on a Scrum Team IIBA Presentation 2010scrummasternz
 
Release Management: Successful Software Releases Start with a Plan
Release Management: Successful Software Releases Start with a PlanRelease Management: Successful Software Releases Start with a Plan
Release Management: Successful Software Releases Start with a Planconnielharper
 
Agile Release Planning
Agile Release PlanningAgile Release Planning
Agile Release PlanningAdnan Aziz
 

Destaque (14)

Riding the Agile Wave
Riding the Agile WaveRiding the Agile Wave
Riding the Agile Wave
 
Workshop empowering teams
Workshop empowering teamsWorkshop empowering teams
Workshop empowering teams
 
Be curious without judging - building a coaching structure
Be curious without judging  - building a coaching structureBe curious without judging  - building a coaching structure
Be curious without judging - building a coaching structure
 
Understanding Scrum
Understanding ScrumUnderstanding Scrum
Understanding Scrum
 
Refactoring Techniques
Refactoring TechniquesRefactoring Techniques
Refactoring Techniques
 
The Value of Refactoring on an Agile Team
The Value of Refactoring on an Agile TeamThe Value of Refactoring on an Agile Team
The Value of Refactoring on an Agile Team
 
Scrum Roles : Scrum Master | Product Owner |Team
Scrum Roles : Scrum Master | Product Owner |TeamScrum Roles : Scrum Master | Product Owner |Team
Scrum Roles : Scrum Master | Product Owner |Team
 
Room to Breathe: The BA's role in project estimation
Room to Breathe: The BA's role in project estimationRoom to Breathe: The BA's role in project estimation
Room to Breathe: The BA's role in project estimation
 
Product Owner Super Powers
Product Owner Super PowersProduct Owner Super Powers
Product Owner Super Powers
 
Agile Development Ultimate Slides
Agile Development Ultimate SlidesAgile Development Ultimate Slides
Agile Development Ultimate Slides
 
Estimating and planning Agile projects
Estimating and planning Agile projectsEstimating and planning Agile projects
Estimating and planning Agile projects
 
The Role of a BA on a Scrum Team IIBA Presentation 2010
The Role of a BA on a Scrum Team IIBA Presentation 2010The Role of a BA on a Scrum Team IIBA Presentation 2010
The Role of a BA on a Scrum Team IIBA Presentation 2010
 
Release Management: Successful Software Releases Start with a Plan
Release Management: Successful Software Releases Start with a PlanRelease Management: Successful Software Releases Start with a Plan
Release Management: Successful Software Releases Start with a Plan
 
Agile Release Planning
Agile Release PlanningAgile Release Planning
Agile Release Planning
 

Semelhante a Introduction to Refactoring

Will Agile work in my embedded development environment?
Will Agile work in my embedded development environment?Will Agile work in my embedded development environment?
Will Agile work in my embedded development environment?bmyllerup
 
Improving the Design of Existing Software
Improving the Design of Existing SoftwareImproving the Design of Existing Software
Improving the Design of Existing SoftwareSteven Smith
 
Behavior driven development - cucumber, Junit and java
Behavior driven development - cucumber, Junit and javaBehavior driven development - cucumber, Junit and java
Behavior driven development - cucumber, Junit and javaNaveen Kumar Singh
 
Empirical proces control
Empirical proces controlEmpirical proces control
Empirical proces controlNiels Verdonk
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing SoftwareSteven Smith
 
How Custom is your Org? CEER at Dreamforce 2019
How Custom is your Org?  CEER at Dreamforce 2019How Custom is your Org?  CEER at Dreamforce 2019
How Custom is your Org? CEER at Dreamforce 2019Steven Herod
 
Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality of Existing SoftwareSteven Smith
 
I Love APIs 2015: End to End Testing: Bug Squashing for Developers
I Love APIs 2015: End to End Testing: Bug Squashing for DevelopersI Love APIs 2015: End to End Testing: Bug Squashing for Developers
I Love APIs 2015: End to End Testing: Bug Squashing for DevelopersApigee | Google Cloud
 
STATIK: Systems Thinking Approach to Introducing Kanban
STATIK: Systems Thinking Approach to Introducing KanbanSTATIK: Systems Thinking Approach to Introducing Kanban
STATIK: Systems Thinking Approach to Introducing KanbanBrad Swanson
 
Decoupling Edutopia.org
Decoupling Edutopia.orgDecoupling Edutopia.org
Decoupling Edutopia.orgdsayswhat
 
Portfolio visualisation Scrum Gathering Prague
Portfolio visualisation Scrum Gathering PraguePortfolio visualisation Scrum Gathering Prague
Portfolio visualisation Scrum Gathering PragueJoanne Perold
 
Thoughts on Lean Product Development at CAMUG, YYC Nov 2014
Thoughts on Lean Product Development at CAMUG, YYC Nov 2014Thoughts on Lean Product Development at CAMUG, YYC Nov 2014
Thoughts on Lean Product Development at CAMUG, YYC Nov 2014Dave Sharrock
 
Debugging PL/SQL with Oracle SQL Developer
Debugging PL/SQL with Oracle SQL DeveloperDebugging PL/SQL with Oracle SQL Developer
Debugging PL/SQL with Oracle SQL DeveloperJeff Smith
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean CodingMetin Ogurlu
 
Comprehensive Validation with Laravel 4
Comprehensive Validation with Laravel 4Comprehensive Validation with Laravel 4
Comprehensive Validation with Laravel 4Kirk Bushell
 
Presentation of agile engineering practices
Presentation of agile engineering practicesPresentation of agile engineering practices
Presentation of agile engineering practicesRoberto Bettazzoni
 
How to design good api
How to design good apiHow to design good api
How to design good apiOsama Shakir
 
The Good Shepherd - the Role of BAs in Agile
The Good Shepherd - the Role of BAs in AgileThe Good Shepherd - the Role of BAs in Agile
The Good Shepherd - the Role of BAs in AgileDave Sharrock
 
Apigility-powered API's on IBM i
Apigility-powered API's on IBM iApigility-powered API's on IBM i
Apigility-powered API's on IBM ichukShirley
 

Semelhante a Introduction to Refactoring (20)

Will Agile work in my embedded development environment?
Will Agile work in my embedded development environment?Will Agile work in my embedded development environment?
Will Agile work in my embedded development environment?
 
Improving the Design of Existing Software
Improving the Design of Existing SoftwareImproving the Design of Existing Software
Improving the Design of Existing Software
 
Behavior driven development - cucumber, Junit and java
Behavior driven development - cucumber, Junit and javaBehavior driven development - cucumber, Junit and java
Behavior driven development - cucumber, Junit and java
 
Empirical proces control
Empirical proces controlEmpirical proces control
Empirical proces control
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
How Custom is your Org? CEER at Dreamforce 2019
How Custom is your Org?  CEER at Dreamforce 2019How Custom is your Org?  CEER at Dreamforce 2019
How Custom is your Org? CEER at Dreamforce 2019
 
Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality of Existing Software
 
I Love APIs 2015: End to End Testing: Bug Squashing for Developers
I Love APIs 2015: End to End Testing: Bug Squashing for DevelopersI Love APIs 2015: End to End Testing: Bug Squashing for Developers
I Love APIs 2015: End to End Testing: Bug Squashing for Developers
 
STATIK: Systems Thinking Approach to Introducing Kanban
STATIK: Systems Thinking Approach to Introducing KanbanSTATIK: Systems Thinking Approach to Introducing Kanban
STATIK: Systems Thinking Approach to Introducing Kanban
 
Decoupling Edutopia.org
Decoupling Edutopia.orgDecoupling Edutopia.org
Decoupling Edutopia.org
 
Portfolio visualisation Scrum Gathering Prague
Portfolio visualisation Scrum Gathering PraguePortfolio visualisation Scrum Gathering Prague
Portfolio visualisation Scrum Gathering Prague
 
How to design effective APIs
How to design effective APIsHow to design effective APIs
How to design effective APIs
 
Thoughts on Lean Product Development at CAMUG, YYC Nov 2014
Thoughts on Lean Product Development at CAMUG, YYC Nov 2014Thoughts on Lean Product Development at CAMUG, YYC Nov 2014
Thoughts on Lean Product Development at CAMUG, YYC Nov 2014
 
Debugging PL/SQL with Oracle SQL Developer
Debugging PL/SQL with Oracle SQL DeveloperDebugging PL/SQL with Oracle SQL Developer
Debugging PL/SQL with Oracle SQL Developer
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean Coding
 
Comprehensive Validation with Laravel 4
Comprehensive Validation with Laravel 4Comprehensive Validation with Laravel 4
Comprehensive Validation with Laravel 4
 
Presentation of agile engineering practices
Presentation of agile engineering practicesPresentation of agile engineering practices
Presentation of agile engineering practices
 
How to design good api
How to design good apiHow to design good api
How to design good api
 
The Good Shepherd - the Role of BAs in Agile
The Good Shepherd - the Role of BAs in AgileThe Good Shepherd - the Role of BAs in Agile
The Good Shepherd - the Role of BAs in Agile
 
Apigility-powered API's on IBM i
Apigility-powered API's on IBM iApigility-powered API's on IBM i
Apigility-powered API's on IBM i
 

Último

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
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 Takeoffsammart93
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
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 WorkerThousandEyes
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 

Último (20)

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 

Introduction to Refactoring

  • 1. Refactoring Improving the design of existing code … …. without changing the behavior! agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 2. Why do good developers write bad software? • Project and budget pressure lead to taking shortcuts • You realize there are better ways to do something • Requirements change over time ! • When it’s hard to change update your code this lead to less optimal design e fix our w How do ? oftware s agile42 | The Agile Coaching Company How do w e know ou r software is “bad” … when it works fin e! www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 3. Software development is not a Jenga game • Single Responsibility Principle • Just because you can, doesn’t mean you should. • Open Closed Principle • Open chest surgery is not needed when putting on a coat. • Liskov Substitution Principle • If it looks like a duck, quacks like a duck,
 but needs batteries – you probably have the wrong abstraction • Interface Segregation Principle • You want me to plug this in, where? • Dependency Inversion Principle • Would you solder a lamp directly to the electrical wiring in a wall? agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 4. Single Responsibility Principle • A responsibility can be defined as a reason to change ! ! ! ! ! ! ! • Just because you can, doesn’t mean you should. agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 5. Open Closed Principle • open for extension, but closed for modification ! ! ! ! ! ! ! • Open chest surgery is not needed when putting on a coat. agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 6. Liskov Substitution Principle • use a subtype without changing the correctness of the program ! ! ! ! ! ! ! • If it looks like a duck, quacks like a duck,
 but needs batteries – you probably have the wrong abstraction agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 7. Interface Segregation Principle • states that no client should be forced to depend on methods it does not use ! ! ! ! ! ! ! • You want me to plug this in, where? agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 8. Dependency Inversion Principle • no dependencies on implementations only on abstractions ! ! ! ! ! ! ! • Would you solder a lamp directly to the electrical wiring in a wall? agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 9. Dependency Inversion Example class EventLogWriter { public void Write(string message) { //Write to event log here } } ! class AppPoolWatcher { // Handle to EventLog writer to write to the logs EventLogWriter writer = null; ! // This function will be called when the app pool has problem public void Notify(string message) { if (writer == null) { writer = new EventLogWriter(); } writer.Write(message); } } agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 10. Dependency Inversion Example EventLogWriter AppPoolWatcher // This can be watcher.Action ! writer = new EventLogWriter(); watcher = new AppPoolWatcher(); done in some class = writer; // This can be done in some other class watcher.Notify("Sample message to log"); agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 11. Dependency Inversion Example class AppPoolWatcher { // Handle to EventLog writer to write to the logs INofificationAction action = null; ! ! public INofificationAction Action { get { return action; } set { action = value; } } // This function will be called when the app pool has problem public void Notify(string message) { action.ActOnNotification(message); } } agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 12. Refactoring Improving the design of existing code Without changing the behavior agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 13. Refactoring Released in 2000, already a golden oldie, a book I recommend everyone to read. ! The book defines the technique of refactoring and is a reference for refactoring types. agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 14. Code Smells Refactoring Cheat Codes agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 15. Code Smells • The term code smells was introduced by Kent Beck, based on an important lesson he learned from his Grandmother about children and diapers.
 
 „If it stinks, change it”—Grandma Beck agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 16. Code Smells • Duplicated Code • Primitive Obsession • Inappropriate Intimacy • Long Method • Switch Statements • Large Class • Parallel Inheritance Hierarchies • Alternative Classes with Different Interfaces • Long Parameter List • Divergent Change • Shotgun Surgery • Feature Envy • Data Clumps agile42 | The Agile Coaching Company • Incomplete Library Class • Lazy Class • Data Class • Speculative Generality • Refused Bequest • Temporary Field • Comments • Middle Man • Dead Code www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 17. Comments and Naming • Comments • Rename Method • Add comments only to explain purpose • Extract Method • If comments need to explain how code work, it smells. ! • Instead use meaningful names, e.g.:
 schedule.add(Course course) ! ! ! ! ! ! • Type Embedded in Name • Rename Method • Uncommunicative Name • Inconsistent Names agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 18. Excess and Duplication • Excess • Long Method • Long Parameter List • Large Class • Long methods, large classes and endless parameters make code unreadable. ! • Duplicated Code • Extract Method • Replace Temp with Query • Introduce Parameter Object • Extract Class • Extract Subclass ! ! ! • Replace Parameter with Method • Pull Up Field • Form Template Method • Substitute Algorithm agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 19. The Past and the Future • Dead Code • Delete Code • or worse, commented code ! • Delete it, we have version control for that! ! ! ! • Speculative Generality • Collapse Hierarchy • Don't attempt to predict future needs with unnecessary generalization. • Inline Class • Remove Parameter • Rename Method YAGNI! agile42 | The Agile Coaching Company KISS www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 20. Rename Method // this method will return the maximum void getMaximumCreditLimit() { // credit limit. return maximumCreditLimit; void getIt() { } return _mCL; void getInvoiceCreditLimit() { } int maximumCredit; void getivcdlmt() { float usedCredit; int m; float u; => . . } . . } agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 21. Extract Method void printOwing(double amount) { void printOwing(double amount) { printBanner(); printBanner(); printDetails(amount); //print details } System.out.println ("name:" + _name); System.out.println ("amount" + amount); } void printDetails (double amount) { => System.out.println ("name:" + _name); System.out.println ("amount" + amount); } agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 22. Replace Temp With Query double basePrice = _quantity * _itemPrice; if (basePrice() > 1000) if (basePrice > 1000) return basePrice() * 0.95; return basePrice * 0.95; else else return basePrice() * 0.98; return basePrice * 0.98; … double basePrice() { => return _quantity * _itemPrice; } agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 23. Introduce Parameter Object double invoicedAmount(Date start, Date end) { double invoicedAmount(Period range) { double result; double result; for (Invoice invoice: invoices) { for (Invoice invoice: invoices) { if (range.contains(invoice.getDate()) { if (invoice.getDate().after(start) || result += invoice.getAmount(); invoice.getDate().before(end)) { } result += invoice.getAmount(); } } return result; } return result; } => ! } class Period (Date start, Date end) { . . . boolean contains(Date date) { return date.after(start) || date.before(end); } } agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 24. Extract Class class Person... public String getName() { class Person... public String getName() { return _name; } public String getTelephoneNumber() { return ("(" + _officeAreaCode + ")" + _officeNumber); } String getOfficeAreaCode() { return _officeAreaCode; } String getOfficeNumber() { return _officeNumber; } private String _name; private String _officeAreaCode; private String _officeNumber; agile42 | The Agile Coaching Company return _name; => ! } public String getTelephoneNumber(){ return _officeTelephone.getTelephoneNumber(); } TelephoneNumber getOfficeTelephone() { return _officeTelephone; } private String _name; private TelephoneNumber _officeTelephone = new TelephoneNumber(); class TelephoneNumber... public String getTelephoneNumber() { return ("(" + _areaCode + ") " + _number); } String getAreaCode() { return _areaCode; String getNumber() { return _number; } private String _number; private String _areaCode; www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 25. Extract Subclass class JobItem ... public JobItem (int unitPrice, class JobItem ... public JobItem (int unitPrice) { boolean isLabor, Employee employee) { _unitPrice = unitPrice; _isLabor = isLabor; _employee = employee; ! } public int getUnitPrice(){ return (_isLabor) ? _employee.getRate(): _unitPrice; } ... class Employee... public Employee (int rate) { _rate = rate; } public int getRate() { return _rate; } private int _rate; _unitPrice = unitPrice; ! => } public int getUnitPrice(){ return _unitPrice; } ... class LaborItem ... public LaborItem (Employee employee) { super(0); _employee = employee; } public int getUnitPrice(){ return_employee.getRate(): } ... ! class Employee... public Employee (int rate) { _rate = rate; } public int getRate() { return _rate; } private int _rate; agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 26. Replace Parameter with Method public double getPrice() { int basePrice = _quantity * _itemPrice; int discountLevel; if (_quantity > 100) discountLevel = 2; else discountLevel = 1; double finalPrice = discountedPrice (basePrice,discountLevel); return finalPrice; } ! private double discountedPrice (int basePrice, int discountLevel) { if (discountLevel == 2) return basePrice * 0.1; else return basePrice * 0.05; } agile42 | The Agile Coaching Company public double getPrice() { if (getDiscountLevel() == 2) return getBasePrice() * 0.1; else return getBasePrice() * 0.05; } ! => private double getBasePrice() { return _quantity * _itemPrice; } ! private int getDiscountLevel() { if (_quantity > 100) return 2; else return 1; } www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 27. Substitute Algorithm String foundPerson(String[] people){ for (int i = 0; i < people.length; i++) { if (people[i].equals ("Don")){ return "Don"; } if (people[i].equals ("John")){ return "John"; } if (people[i].equals ("Kent")){ return "Kent"; } } return ""; } => String foundPerson(String[] people){ List candidates = Arrays.asList(new String[] {"Don", "John", "Kent"}); for (int i=0; i &lt; people.length; i++) if (candidates.contains(people[i])) return people[i]; return ""; } agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.
  • 28. References • SOLID:
 http://en.wikipedia.org/wiki/SOLID_(object-oriented_design) ! • SmellsToRefactorings:
 http://users.csc.calpoly.edu/~jdalbey/305/Lectures/SmellsToRefactorings ! • Martin Fowler refactoring site: http://refactoring.com/ ! • Dependency Injection: http://martinfowler.com/articles/injection.html agile42 | The Agile Coaching Company www.agile42.com | All rights reserved. Copyright © 2007 - 2014.