SlideShare ist ein Scribd-Unternehmen logo
1 von 43
Downloaden Sie, um offline zu lesen
REFACTORING
Improving the Design of Existing code
Software Engineering II Class (Lect. 6)
Valerio Maggio, Ph.D. Student
A.A. 2011/12
Prof. Marco Faella
• What does “Refactoring” means?
‣ When should you refactor your code/design?
‣ Why should you refactor your code/design?
‣ Refactoring Principles
• Typical Refactorings
• Bad Smells & Solutions
OUTLINE
(CODE) REFACTORING
• The art of safely improving the design of existing code [Fowler09]
• Implications: [Fowler09]
‣ Refactoring does not include any change to the system
‣ Refactoring is not “Rewriting from scratch”
‣ Refactoring is not just any restructuring intended to improve the code
Refactoring: (Definition) Refactoring is the process of changing a
software system in such a way that it does not alter the external behavior of
the code yet improves its internal structure. [Fowler02]
REFACTORING
• Basic Metaphor:
‣ Start with an existing code and make it better;
‣ Change the internal structure while preserving the overall
semantics.
• Goals:
‣ Reduce near-duplicate code
‣ Improve comprehension and maintainability while reducing
coupling
THE REFACTORING CYCLE
start with working, tested code
while the design can be simplified do:
choose the worst smell
select a refactoring that addresses that smell
apply the refactoring
check that the tests still pass
•KWs:
•Tested Code
‣Importance of Testing in Refactoring
‣Why testing?
•(Code) Smells
‣Fragments of code that contain some design mistake
• Refactor when you add a function
• Refactor when you fix a bug
• Refactor for Greater Understanding
WHEN SHOULDYOU
REFACTOR?
The Rule of Three: The first time you do something, you just do it.
The second time you do something similar, you wince at the duplication, but
you do the duplicate thing anyway. The third time you do something similar,
you refactor. [Fowler09]
• Refactoring improves the design of software
‣ Without refactoring the design of the program will decay
‣ Poorly designed code usually takes more code to do the
same things
• Refactoring makes software easier to understand
‣ In most software development environments, somebody
else will eventually have to read your code
• Refactoring helps you find bugs
WHY SHOULDYOU
REFACTOR?
• Programs that are hard to read, are hard to modify.
• Programs that have duplicated logic, are hard to modify.
• Programs that require additional behavior requiring changing
code are hard to modify.
• Programs with complex conditional logic are hard to modify.
• Refactoring makes code more readable
WHY REFACTORING WORKS?
Good O-O Practices
REFACTORING
• Short methods
‣ Simple method logic
• Few instance variables
• Clear object responsibilities
‣ State the purpose of the class in one sentence
‣ No super-intelligent objects
GOOD SIGNS OF OO
THINKING
• The Dependency Inversion Principle
‣Depend on abstractions, not concrete implementations
•Write to an interface, not a class
• The Interface Segregation Principle
‣Many small interfaces are better than one “fat” one
• The Acyclic Dependencies Principle
‣Dependencies between package must not form cycles.
•Break cycles by forming new packages
SOME PRINCIPLES
• The Common Closure Principle
‣Classes that change together, belong together
•Classes within a released component should share common
closure.That is, if one needs to be changed, they all are likely
to need to be changed.
• The Common Reuse Principle
‣Classes that aren’t reused together don’t belong together
•The classes in a package are reused together. If you reuse
one of the classes in a package, you reuse them all.
PACKAGES, MODULES AND
OTHER
TYPICAL REFACTORINGS
Refactoring in Action
REFACTORINGSTABLE
Class Refactorings Method Refactorings
Attribute
Refactorings
add (sub)class to hierarchy add method to class add variable to class
rename class rename method rename variable
remove class remove method remove variable
extract class push method down push variable down
push method up pull variable up
add parameter to method create accessors
move method abstract variable
extract code in new method
replace parameter with method
• Behavior on a superclass is relevant only for some of its
subclasses.
• Move it to those subclasses.
PUSH METHOD DOWN
Engineer
+ getQuota()
SalesMan
Employee
+ getQuota()
Employee
Salesman Engineer
• You have methods with identical results on subclasses.
• Move them to the superclass
PUSH METHOD UP
+ getName()
Salesman
Employee
+ getName()
Engineer
+ getName()
Employee
Salesman Engineer
• A method needs more information from its caller.
• Add a parameter for an object that can pass on this
information.
ADD PARAMETERTO
METHOD
+getContact()
Customer
+getContact(Date)
Customer
EXTRACT METHOD
void printOwing() {

 printBanner();

 //print details

 System.out.println ("name:
 " + _name);
System.out.println ("amount
 " + getOutstanding());
}
void printOwing() {

 printBanner();
printDetails(getOutstanding());
}
void printDetails (double outstanding) {
System.out.println ("name: " + _name);
System.out.println ("amount " + outstanding);
}
BAD SMELLS IN CODE
If it stinks, change it.
BAD SMELLS IN CODE
• By now you have idea of what refactoring is!
• But, you have no concrete indication on when refactoring
should be applied!
Bad Smells: (General Definition) Pieces of code that are
wrong (in some sense) and that are ugly to see. [Fowler09]
BAD SMELLS IN CODE (1)
Symptoms Bad Smell Name
Missing Inheritance or delegation Duplicated code
Inadequate decomposition Long Method
Too many responsibility Large/God Class
Object is missing Long Parameter List
Missing polymorphism TypeTests
BAD SMELLS IN CODE (2)
Symptoms Bad Smell Name
Same class changes differently
depending on addition
Divergent Change
Small changes affects too many
objects
Shotgun Surgery
Method needing too much
information from another object
Feature Envy
Data that are always used together Data Clumps
Changes in one hierarchy require
change in another hierarchy
Parallel Inheritance Hierarchy
BAD SMELLS IN CODE (3)
Symptoms Bad Smell Name
Class that does too little Lazy Class
Class with too many delegating
methods
Middle Man
Attributes only used partially under
certain circumstances
Temporary Field
Coupled classes, internal
representation dependencies
Message Chains
Class containing only accessors Data Classes
DUPLICATED CODE
Problem: Finding the same code structure
in more than one place
Solution: Perform Extract Method and
invoke the code from both places
Problem: Having the same expression in
two sibling subclasses
Solution: Perform Extract Method in both
classes and the Pull Up Field
(a)
(b)
LONG METHOD
Problem: Finding a very long method
Solution: Perform Extract Method
and improve responsibilities distribution
Problem: Finding a very long method whose
statements operates on different parameters/variables
Solution: Extract Class
(a)
(b)
LARGE CLASS
Problem: Finding a class that does too much (too
many responsibilities)
Solution: Perform Extract (Sub)Class and improve
responsibilities distribution
Rule of Thumb:
• When a class is trying to do too much, it often
shows up as too many instance variables.
• When a class has too many instance variables,
duplicated code cannot be far behind
LONG PARAMETER LIST
Problem: Finding a method that has a very long
parameter list
Solution: Replace Parameters with Methods
or Introduce Parameter Object
‣ [Old School] Pass everything as a parameter
instead of using global data.
public void marry(String name, int age,
boolean gender, String name2,
int age2, boolean gender2) {...}
DIVERGENT CHANGE
Problem: Divergent change occurs when one
class is commonly changed in different ways for
different reasons
Solution: identify everything that changes for a
particular cause and use Extract Class to put them
all together
‣ Violation of Separation of Concerns principle
SHOTGUN SURGERY
Problem: Every time you make a kind of change, you
have to make a lot of little changes to a lot of different
classes.
Solution: Use Move Method and Move Field to
put all the changes in a single class.
• When the changes are all over the place they are
hard to find, and its easy to miss an important change.
• Results of Copy&Paste programming
FEATURE ENVY
A classic [code] smell is a method that seems more interested
in a class other than the one it is in.The most common focus
of the envy is the data. [Fowler02]
Problem: Finding a (part of a) method that makes heavy use
of data and methods from another class
Solution: Use Move/Extract Method to put it
in the more desired class.
DATA CLUMPS
Problem: Finding same three or four data items together
in lots of places (Fields in a couple of classes,
Parameters in many method signatures)
Solution (1): look for where the clumps appear as fields
and use Extract Class to turn the clumps into an object
Solution (2): For method parameters use Introduce
Parameter Object to slim them down
PRIMITIVE OBSESSION
People new to objects are sometimes reluctant to use small objects
for small tasks, such as money classes that combine numbers and
currency ranges with an upper and lower.
Problem: Your primitive needs any additional data or
behavior.
Solution: Use Extract Class to turn primitives
into a Class.
TYPE TESTS
Problem: Finding a switch statement checking the
type of an instance object (no Polymorphism).
Solution: Use Extract Method to extract the switch
statement and then Move Method to get it into the
class where the polymorphism is needed
The essence of polymorphism is that instead of asking an
object what type it is and then invoking some behavior
based on the answer, you just invoke the behavior.
PARALLEL INHERITANCE
HIERARCHIES
Problem: every time you make a subclass of one class, you
have to make a subclass of another (special case of Shotgun
Surgery).
Solution: Use Move Method and Move Field to
collapse pairwise features and remove duplications.
LAZY CLASS
Problem: Finding a class that is not doing “enough”.
Solution: If you have subclasses that are not doing
enough try to use Collapse Hierarchy and nearly
useless components should be subjected to Inline Class
SPECULATIVE GENERALIZATION
Problem: You get this smell when someone says "I think we
need the ability to do this someday" and you need all sorts of
hooks and special cases to handle things that are not required.
Solution:
(1) If you have abstract classes that are not doing enough then use
Collapse Hierarchy
(2) Unnecessary delegation can be removed with Inline Class
(3) Methods with unused parameters should be subject to
Remove Parameter
(4) Methods named with odd abstract names should be repaired
with Rename Method
TEMPORARY FIELD
Problem: Finding an object in which an instance
variable is set only in certain circumstances.
(We usually expect an object to use all of its variables)
Solution: Use Extract Class to create a home for
these orphan variables by putting all the code that uses the
variable into the component.
MESSAGE CHAINS
Problem: Message chains occur when you see a client that
asks one object for another object, which the client then asks
for yet another object, which the client then asks for yet
another object, etc.
intermediate.getProvider().doSomething()
ch = vehicle->getChassis();
body = ch->getBody();
shell = body->getShell();
material = shell->getMaterial();
props = material->getProperties();
color = props->getColor();
ELIMINATE NAVIGATION CODE
…
engine.carburetor.fuelValveOpen = true
Engine
+carburetor
Car
-engine
+increaseSpeed()
Carburetor
+fuelValveOpen
Engine
-carburetor
+speedUp()
Car
-engine
+increaseSpeed()
…
engine.speedUp()
carburetor.fuelValveOpen = true
Carburetor
+fuelValveOpen
Car
-engine
+increaseSpeed()
Carburetor
-fuelValveOpen
+openFuelValve()
Engine
-carburetor
+speedUp()
carburetor.openFuelValve()fuelValveOpen = true
• One the major features of Objects is encapsulation
• Encapsulation often comes with delegation
• Sometimes delegation can go to far
• For example if you find half the methods are delegated to
another class it might be time to use Remove Middle Man and
talk to the object that really knows what is going on
• If only a few methods are not doing much, use Inline Method to
inline them into the caller
• If there is additional behavior, you can use Replace Delegation
with Inheritance to turn the middle man into a subclass of the
real object
MIDDLE MAN
REMOVE MIDDLE MAN
Client
Department
+getManager()
Person
Client
+getDepartment()
Person
+getManager()
Department
WHAT’S NEXT?
• In the next class, we will:
a. Analyze together a (quite) real case study.
b.Focus on the design of each (Java) class
c. Apply some Refactoring directly into an IDE
• to understand what “Refactoring” means in practice
• to see Refactoring features embedded into Eclipse
REFERENCES
• [Fowler02] M. Fowler, K. Beck; Refactoring:
Improving the Design of Existing Code, Addison
Wesley, 2002
• [Fowler09] J. Fields, S. Harvie, M.Fowler, K. Beck;
Refactoring in Ruby,Addison Wesley, 2009
• http://martinfowler.com/refactoring/catalog/
index.html

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Refactoring Techniques
Refactoring TechniquesRefactoring Techniques
Refactoring Techniques
 
Refactoring
RefactoringRefactoring
Refactoring
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoring
 
Code smell overview
Code smell overviewCode smell overview
Code smell overview
 
Code Smells and Its type (With Example)
Code Smells and Its type (With Example)Code Smells and Its type (With Example)
Code Smells and Its type (With Example)
 
Clean code
Clean codeClean code
Clean code
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code Principles
 
Clean code
Clean codeClean code
Clean code
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Code Smells
Code SmellsCode Smells
Code Smells
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
 
Clean code
Clean codeClean code
Clean code
 
The Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable DesignThe Art of Unit Testing - Towards a Testable Design
The Art of Unit Testing - Towards a Testable Design
 
Solid Principles & Design patterns with PHP examples
Solid Principles & Design patterns with PHP examplesSolid Principles & Design patterns with PHP examples
Solid Principles & Design patterns with PHP examples
 
Git and Github slides.pdf
Git and Github slides.pdfGit and Github slides.pdf
Git and Github slides.pdf
 
Clean code
Clean codeClean code
Clean code
 
Clean code
Clean codeClean code
Clean code
 
Clean Code
Clean CodeClean Code
Clean Code
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
 

Andere mochten auch

Refactoring - An Introduction
Refactoring - An IntroductionRefactoring - An Introduction
Refactoring - An IntroductionGiorgio Vespucci
 
Refactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech TalkRefactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech TalkGanesh Samarthyam
 
Big code refactoring with agility
Big code refactoring with agilityBig code refactoring with agility
Big code refactoring with agilityLuca Merolla
 
When and Why Your Code Starts to Smell Bad
When and Why Your Code Starts to Smell BadWhen and Why Your Code Starts to Smell Bad
When and Why Your Code Starts to Smell BadFabio Palomba
 
Refactoring legacy code: step-by-step examples
Refactoring legacy code: step-by-step examplesRefactoring legacy code: step-by-step examples
Refactoring legacy code: step-by-step examplesEndava
 
Refactoring for Software Design Smells
Refactoring for Software Design SmellsRefactoring for Software Design Smells
Refactoring for Software Design SmellsGanesh Samarthyam
 
Principles in Refactoring
Principles in RefactoringPrinciples in Refactoring
Principles in RefactoringChamnap Chhorn
 
Unsupervised Machine Learning for clone detection
Unsupervised Machine Learning for clone detectionUnsupervised Machine Learning for clone detection
Unsupervised Machine Learning for clone detectionValerio Maggio
 
Code refactoring
Code refactoringCode refactoring
Code refactoringLalit Kale
 
An Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersAn Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersKostas Saidis
 

Andere mochten auch (12)

Refactoring - An Introduction
Refactoring - An IntroductionRefactoring - An Introduction
Refactoring - An Introduction
 
Refactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech TalkRefactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech Talk
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoring
 
Big code refactoring with agility
Big code refactoring with agilityBig code refactoring with agility
Big code refactoring with agility
 
When and Why Your Code Starts to Smell Bad
When and Why Your Code Starts to Smell BadWhen and Why Your Code Starts to Smell Bad
When and Why Your Code Starts to Smell Bad
 
Refactoring legacy code: step-by-step examples
Refactoring legacy code: step-by-step examplesRefactoring legacy code: step-by-step examples
Refactoring legacy code: step-by-step examples
 
Refactoring for Software Design Smells
Refactoring for Software Design SmellsRefactoring for Software Design Smells
Refactoring for Software Design Smells
 
Principles in Refactoring
Principles in RefactoringPrinciples in Refactoring
Principles in Refactoring
 
Unsupervised Machine Learning for clone detection
Unsupervised Machine Learning for clone detectionUnsupervised Machine Learning for clone detection
Unsupervised Machine Learning for clone detection
 
Code refactoring
Code refactoringCode refactoring
Code refactoring
 
Gradle
GradleGradle
Gradle
 
An Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersAn Introduction to Groovy for Java Developers
An Introduction to Groovy for Java Developers
 

Ähnlich wie Refactoring: Improve the design of existing code

Agile korea 2013 유석문
Agile korea 2013 유석문Agile korea 2013 유석문
Agile korea 2013 유석문Sangcheol Hwang
 
Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기Myeongseok Baek
 
Bade Smells in Code
Bade Smells in CodeBade Smells in Code
Bade Smells in CodeWill Shen
 
Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif IqbalCode Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif IqbalCefalo
 
Getting Unstuck: Working with Legacy Code and Data
Getting Unstuck: Working with Legacy Code and DataGetting Unstuck: Working with Legacy Code and Data
Getting Unstuck: Working with Legacy Code and DataCory Foy
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And RefactoringNaresh Jain
 
Few minutes To better Code - Refactoring
Few minutes To better Code - RefactoringFew minutes To better Code - Refactoring
Few minutes To better Code - RefactoringDiaa Al-Salehi
 
Episode 3 – Classes, Inheritance, Abstract Class, and Interfaces
Episode 3 – Classes, Inheritance, Abstract Class, and InterfacesEpisode 3 – Classes, Inheritance, Abstract Class, and Interfaces
Episode 3 – Classes, Inheritance, Abstract Class, and InterfacesJitendra Zaa
 
Improving your code design using Java
Improving your code design using JavaImproving your code design using Java
Improving your code design using JavaRoan Brasil Monteiro
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoringkim.mens
 
Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, H...
Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, H...Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, H...
Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, H...Justin Gordon
 
Speeding up web_application
Speeding up web_applicationSpeeding up web_application
Speeding up web_applicationAchintya Kumar
 
Code Refactoring using rails
Code Refactoring using railsCode Refactoring using rails
Code Refactoring using railsAchintya Kumar
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentationBhavin Gandhi
 
Refactoring workshop
Refactoring workshop Refactoring workshop
Refactoring workshop Itzik Saban
 
Refactoring: Improving the design of existing code
Refactoring: Improving the design of existing codeRefactoring: Improving the design of existing code
Refactoring: Improving the design of existing codeKnoldus Inc.
 

Ähnlich wie Refactoring: Improve the design of existing code (20)

Agile korea 2013 유석문
Agile korea 2013 유석문Agile korea 2013 유석문
Agile korea 2013 유석문
 
Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기Ddc2011 효과적으로레거시코드다루기
Ddc2011 효과적으로레거시코드다루기
 
Bade Smells in Code
Bade Smells in CodeBade Smells in Code
Bade Smells in Code
 
Refactoring
RefactoringRefactoring
Refactoring
 
Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif IqbalCode Smells and Refactoring - Satyajit Dey & Ashif Iqbal
Code Smells and Refactoring - Satyajit Dey & Ashif Iqbal
 
Getting Unstuck: Working with Legacy Code and Data
Getting Unstuck: Working with Legacy Code and DataGetting Unstuck: Working with Legacy Code and Data
Getting Unstuck: Working with Legacy Code and Data
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
 
Few minutes To better Code - Refactoring
Few minutes To better Code - RefactoringFew minutes To better Code - Refactoring
Few minutes To better Code - Refactoring
 
Episode 3 – Classes, Inheritance, Abstract Class, and Interfaces
Episode 3 – Classes, Inheritance, Abstract Class, and InterfacesEpisode 3 – Classes, Inheritance, Abstract Class, and Interfaces
Episode 3 – Classes, Inheritance, Abstract Class, and Interfaces
 
Reduce Reuse Refactor
Reduce Reuse RefactorReduce Reuse Refactor
Reduce Reuse Refactor
 
Improving your code design using Java
Improving your code design using JavaImproving your code design using Java
Improving your code design using Java
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoring
 
Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, H...
Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, H...Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, H...
Rails Conf 2014 Concerns, Decorators, Presenters, Service-objects, Helpers, H...
 
Speeding up web_application
Speeding up web_applicationSpeeding up web_application
Speeding up web_application
 
Code Refactoring using rails
Code Refactoring using railsCode Refactoring using rails
Code Refactoring using rails
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
Refactoring workshop
Refactoring workshop Refactoring workshop
Refactoring workshop
 
Bad Smell In Codes 1
Bad Smell In Codes 1Bad Smell In Codes 1
Bad Smell In Codes 1
 
Refactoring: Improving the design of existing code
Refactoring: Improving the design of existing codeRefactoring: Improving the design of existing code
Refactoring: Improving the design of existing code
 
Refactoring
RefactoringRefactoring
Refactoring
 

Mehr von Valerio Maggio

Improving Software Maintenance using Unsupervised Machine Learning techniques
Improving Software Maintenance using Unsupervised Machine Learning techniquesImproving Software Maintenance using Unsupervised Machine Learning techniques
Improving Software Maintenance using Unsupervised Machine Learning techniquesValerio Maggio
 
Number Crunching in Python
Number Crunching in PythonNumber Crunching in Python
Number Crunching in PythonValerio Maggio
 
Clone detection in Python
Clone detection in PythonClone detection in Python
Clone detection in PythonValerio Maggio
 
Machine Learning for Software Maintainability
Machine Learning for Software MaintainabilityMachine Learning for Software Maintainability
Machine Learning for Software MaintainabilityValerio Maggio
 
LINSEN an efficient approach to split identifiers and expand abbreviations
LINSEN an efficient approach to split identifiers and expand abbreviationsLINSEN an efficient approach to split identifiers and expand abbreviations
LINSEN an efficient approach to split identifiers and expand abbreviationsValerio Maggio
 
A Tree Kernel based approach for clone detection
A Tree Kernel based approach for clone detectionA Tree Kernel based approach for clone detection
A Tree Kernel based approach for clone detectionValerio Maggio
 
Scaffolding with JMock
Scaffolding with JMockScaffolding with JMock
Scaffolding with JMockValerio Maggio
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with JunitValerio Maggio
 
Design patterns and Refactoring
Design patterns and RefactoringDesign patterns and Refactoring
Design patterns and RefactoringValerio Maggio
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentValerio Maggio
 
Unit testing and scaffolding
Unit testing and scaffoldingUnit testing and scaffolding
Unit testing and scaffoldingValerio Maggio
 

Mehr von Valerio Maggio (13)

Improving Software Maintenance using Unsupervised Machine Learning techniques
Improving Software Maintenance using Unsupervised Machine Learning techniquesImproving Software Maintenance using Unsupervised Machine Learning techniques
Improving Software Maintenance using Unsupervised Machine Learning techniques
 
Number Crunching in Python
Number Crunching in PythonNumber Crunching in Python
Number Crunching in Python
 
Clone detection in Python
Clone detection in PythonClone detection in Python
Clone detection in Python
 
Machine Learning for Software Maintainability
Machine Learning for Software MaintainabilityMachine Learning for Software Maintainability
Machine Learning for Software Maintainability
 
LINSEN an efficient approach to split identifiers and expand abbreviations
LINSEN an efficient approach to split identifiers and expand abbreviationsLINSEN an efficient approach to split identifiers and expand abbreviations
LINSEN an efficient approach to split identifiers and expand abbreviations
 
A Tree Kernel based approach for clone detection
A Tree Kernel based approach for clone detectionA Tree Kernel based approach for clone detection
A Tree Kernel based approach for clone detection
 
Scaffolding with JMock
Scaffolding with JMockScaffolding with JMock
Scaffolding with JMock
 
Junit in action
Junit in actionJunit in action
Junit in action
 
Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with Junit
 
Design patterns and Refactoring
Design patterns and RefactoringDesign patterns and Refactoring
Design patterns and Refactoring
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Unit testing and scaffolding
Unit testing and scaffoldingUnit testing and scaffolding
Unit testing and scaffolding
 
Web frameworks
Web frameworksWeb frameworks
Web frameworks
 

Kürzlich hochgeladen

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
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
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Kürzlich hochgeladen (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
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
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Refactoring: Improve the design of existing code

  • 1. REFACTORING Improving the Design of Existing code Software Engineering II Class (Lect. 6) Valerio Maggio, Ph.D. Student A.A. 2011/12 Prof. Marco Faella
  • 2. • What does “Refactoring” means? ‣ When should you refactor your code/design? ‣ Why should you refactor your code/design? ‣ Refactoring Principles • Typical Refactorings • Bad Smells & Solutions OUTLINE
  • 3. (CODE) REFACTORING • The art of safely improving the design of existing code [Fowler09] • Implications: [Fowler09] ‣ Refactoring does not include any change to the system ‣ Refactoring is not “Rewriting from scratch” ‣ Refactoring is not just any restructuring intended to improve the code Refactoring: (Definition) Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure. [Fowler02]
  • 4. REFACTORING • Basic Metaphor: ‣ Start with an existing code and make it better; ‣ Change the internal structure while preserving the overall semantics. • Goals: ‣ Reduce near-duplicate code ‣ Improve comprehension and maintainability while reducing coupling
  • 5. THE REFACTORING CYCLE start with working, tested code while the design can be simplified do: choose the worst smell select a refactoring that addresses that smell apply the refactoring check that the tests still pass •KWs: •Tested Code ‣Importance of Testing in Refactoring ‣Why testing? •(Code) Smells ‣Fragments of code that contain some design mistake
  • 6. • Refactor when you add a function • Refactor when you fix a bug • Refactor for Greater Understanding WHEN SHOULDYOU REFACTOR? The Rule of Three: The first time you do something, you just do it. The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyway. The third time you do something similar, you refactor. [Fowler09]
  • 7. • Refactoring improves the design of software ‣ Without refactoring the design of the program will decay ‣ Poorly designed code usually takes more code to do the same things • Refactoring makes software easier to understand ‣ In most software development environments, somebody else will eventually have to read your code • Refactoring helps you find bugs WHY SHOULDYOU REFACTOR?
  • 8. • Programs that are hard to read, are hard to modify. • Programs that have duplicated logic, are hard to modify. • Programs that require additional behavior requiring changing code are hard to modify. • Programs with complex conditional logic are hard to modify. • Refactoring makes code more readable WHY REFACTORING WORKS?
  • 10. • Short methods ‣ Simple method logic • Few instance variables • Clear object responsibilities ‣ State the purpose of the class in one sentence ‣ No super-intelligent objects GOOD SIGNS OF OO THINKING
  • 11. • The Dependency Inversion Principle ‣Depend on abstractions, not concrete implementations •Write to an interface, not a class • The Interface Segregation Principle ‣Many small interfaces are better than one “fat” one • The Acyclic Dependencies Principle ‣Dependencies between package must not form cycles. •Break cycles by forming new packages SOME PRINCIPLES
  • 12. • The Common Closure Principle ‣Classes that change together, belong together •Classes within a released component should share common closure.That is, if one needs to be changed, they all are likely to need to be changed. • The Common Reuse Principle ‣Classes that aren’t reused together don’t belong together •The classes in a package are reused together. If you reuse one of the classes in a package, you reuse them all. PACKAGES, MODULES AND OTHER
  • 14. REFACTORINGSTABLE Class Refactorings Method Refactorings Attribute Refactorings add (sub)class to hierarchy add method to class add variable to class rename class rename method rename variable remove class remove method remove variable extract class push method down push variable down push method up pull variable up add parameter to method create accessors move method abstract variable extract code in new method replace parameter with method
  • 15. • Behavior on a superclass is relevant only for some of its subclasses. • Move it to those subclasses. PUSH METHOD DOWN Engineer + getQuota() SalesMan Employee + getQuota() Employee Salesman Engineer
  • 16. • You have methods with identical results on subclasses. • Move them to the superclass PUSH METHOD UP + getName() Salesman Employee + getName() Engineer + getName() Employee Salesman Engineer
  • 17. • A method needs more information from its caller. • Add a parameter for an object that can pass on this information. ADD PARAMETERTO METHOD +getContact() Customer +getContact(Date) Customer
  • 18. EXTRACT METHOD void printOwing() { printBanner(); //print details System.out.println ("name: " + _name); System.out.println ("amount " + getOutstanding()); } void printOwing() { printBanner(); printDetails(getOutstanding()); } void printDetails (double outstanding) { System.out.println ("name: " + _name); System.out.println ("amount " + outstanding); }
  • 19. BAD SMELLS IN CODE If it stinks, change it.
  • 20. BAD SMELLS IN CODE • By now you have idea of what refactoring is! • But, you have no concrete indication on when refactoring should be applied! Bad Smells: (General Definition) Pieces of code that are wrong (in some sense) and that are ugly to see. [Fowler09]
  • 21. BAD SMELLS IN CODE (1) Symptoms Bad Smell Name Missing Inheritance or delegation Duplicated code Inadequate decomposition Long Method Too many responsibility Large/God Class Object is missing Long Parameter List Missing polymorphism TypeTests
  • 22. BAD SMELLS IN CODE (2) Symptoms Bad Smell Name Same class changes differently depending on addition Divergent Change Small changes affects too many objects Shotgun Surgery Method needing too much information from another object Feature Envy Data that are always used together Data Clumps Changes in one hierarchy require change in another hierarchy Parallel Inheritance Hierarchy
  • 23. BAD SMELLS IN CODE (3) Symptoms Bad Smell Name Class that does too little Lazy Class Class with too many delegating methods Middle Man Attributes only used partially under certain circumstances Temporary Field Coupled classes, internal representation dependencies Message Chains Class containing only accessors Data Classes
  • 24. DUPLICATED CODE Problem: Finding the same code structure in more than one place Solution: Perform Extract Method and invoke the code from both places Problem: Having the same expression in two sibling subclasses Solution: Perform Extract Method in both classes and the Pull Up Field (a) (b)
  • 25. LONG METHOD Problem: Finding a very long method Solution: Perform Extract Method and improve responsibilities distribution Problem: Finding a very long method whose statements operates on different parameters/variables Solution: Extract Class (a) (b)
  • 26. LARGE CLASS Problem: Finding a class that does too much (too many responsibilities) Solution: Perform Extract (Sub)Class and improve responsibilities distribution Rule of Thumb: • When a class is trying to do too much, it often shows up as too many instance variables. • When a class has too many instance variables, duplicated code cannot be far behind
  • 27. LONG PARAMETER LIST Problem: Finding a method that has a very long parameter list Solution: Replace Parameters with Methods or Introduce Parameter Object ‣ [Old School] Pass everything as a parameter instead of using global data. public void marry(String name, int age, boolean gender, String name2, int age2, boolean gender2) {...}
  • 28. DIVERGENT CHANGE Problem: Divergent change occurs when one class is commonly changed in different ways for different reasons Solution: identify everything that changes for a particular cause and use Extract Class to put them all together ‣ Violation of Separation of Concerns principle
  • 29. SHOTGUN SURGERY Problem: Every time you make a kind of change, you have to make a lot of little changes to a lot of different classes. Solution: Use Move Method and Move Field to put all the changes in a single class. • When the changes are all over the place they are hard to find, and its easy to miss an important change. • Results of Copy&Paste programming
  • 30. FEATURE ENVY A classic [code] smell is a method that seems more interested in a class other than the one it is in.The most common focus of the envy is the data. [Fowler02] Problem: Finding a (part of a) method that makes heavy use of data and methods from another class Solution: Use Move/Extract Method to put it in the more desired class.
  • 31. DATA CLUMPS Problem: Finding same three or four data items together in lots of places (Fields in a couple of classes, Parameters in many method signatures) Solution (1): look for where the clumps appear as fields and use Extract Class to turn the clumps into an object Solution (2): For method parameters use Introduce Parameter Object to slim them down
  • 32. PRIMITIVE OBSESSION People new to objects are sometimes reluctant to use small objects for small tasks, such as money classes that combine numbers and currency ranges with an upper and lower. Problem: Your primitive needs any additional data or behavior. Solution: Use Extract Class to turn primitives into a Class.
  • 33. TYPE TESTS Problem: Finding a switch statement checking the type of an instance object (no Polymorphism). Solution: Use Extract Method to extract the switch statement and then Move Method to get it into the class where the polymorphism is needed The essence of polymorphism is that instead of asking an object what type it is and then invoking some behavior based on the answer, you just invoke the behavior.
  • 34. PARALLEL INHERITANCE HIERARCHIES Problem: every time you make a subclass of one class, you have to make a subclass of another (special case of Shotgun Surgery). Solution: Use Move Method and Move Field to collapse pairwise features and remove duplications.
  • 35. LAZY CLASS Problem: Finding a class that is not doing “enough”. Solution: If you have subclasses that are not doing enough try to use Collapse Hierarchy and nearly useless components should be subjected to Inline Class
  • 36. SPECULATIVE GENERALIZATION Problem: You get this smell when someone says "I think we need the ability to do this someday" and you need all sorts of hooks and special cases to handle things that are not required. Solution: (1) If you have abstract classes that are not doing enough then use Collapse Hierarchy (2) Unnecessary delegation can be removed with Inline Class (3) Methods with unused parameters should be subject to Remove Parameter (4) Methods named with odd abstract names should be repaired with Rename Method
  • 37. TEMPORARY FIELD Problem: Finding an object in which an instance variable is set only in certain circumstances. (We usually expect an object to use all of its variables) Solution: Use Extract Class to create a home for these orphan variables by putting all the code that uses the variable into the component.
  • 38. MESSAGE CHAINS Problem: Message chains occur when you see a client that asks one object for another object, which the client then asks for yet another object, which the client then asks for yet another object, etc. intermediate.getProvider().doSomething() ch = vehicle->getChassis(); body = ch->getBody(); shell = body->getShell(); material = shell->getMaterial(); props = material->getProperties(); color = props->getColor();
  • 39. ELIMINATE NAVIGATION CODE … engine.carburetor.fuelValveOpen = true Engine +carburetor Car -engine +increaseSpeed() Carburetor +fuelValveOpen Engine -carburetor +speedUp() Car -engine +increaseSpeed() … engine.speedUp() carburetor.fuelValveOpen = true Carburetor +fuelValveOpen Car -engine +increaseSpeed() Carburetor -fuelValveOpen +openFuelValve() Engine -carburetor +speedUp() carburetor.openFuelValve()fuelValveOpen = true
  • 40. • One the major features of Objects is encapsulation • Encapsulation often comes with delegation • Sometimes delegation can go to far • For example if you find half the methods are delegated to another class it might be time to use Remove Middle Man and talk to the object that really knows what is going on • If only a few methods are not doing much, use Inline Method to inline them into the caller • If there is additional behavior, you can use Replace Delegation with Inheritance to turn the middle man into a subclass of the real object MIDDLE MAN
  • 42. WHAT’S NEXT? • In the next class, we will: a. Analyze together a (quite) real case study. b.Focus on the design of each (Java) class c. Apply some Refactoring directly into an IDE • to understand what “Refactoring” means in practice • to see Refactoring features embedded into Eclipse
  • 43. REFERENCES • [Fowler02] M. Fowler, K. Beck; Refactoring: Improving the Design of Existing Code, Addison Wesley, 2002 • [Fowler09] J. Fields, S. Harvie, M.Fowler, K. Beck; Refactoring in Ruby,Addison Wesley, 2009 • http://martinfowler.com/refactoring/catalog/ index.html