Refactoring
Refactoring
Software Refactoring
Tom Mens
                      •   Goal
                           – To introduce and explain the technique of
                             software refactoring and to explain its importance
Tom Mens, UMH, 2005
                      •   Overview
                           – What is it?
                           – Why is it needed?
                           – When should we do it?
                           – How can it be automated?
                           – Categories of refactorings
       2
3
    Tom Mens, UMH, 2005
                            Books
                          References
                      References
                        Books
                            •   A marriage of
                                refactoring with
                                design patterns
Tom Mens, UMH, 2005
                      •
                          frameworks
                           – University of Illinois at Urbana-Champaign, USA, 1992
                      •   I. Moore. Automatic restructuring of object-
                          oriented programs
                           – Manchester University, UK, 1996
                      •   D. Roberts. Practical Analysis for Refactoring
                           – University of Illinois at Urbana-Champaign, 1999
                      •   S. Tichelaar. Modeling object-oriented software for
                          reverse engineering and refactoring
       5
                           – University of Bern, Switzerland, 2001
                                           References
                                     selected journal articles
                      • What is refactoring?
                      • Why is it needed?
                      • When do we need to refactor?
Tom Mens, UMH, 2005
       7
                                        What is refactoring?
                      •   Some definitions
                           – [Fowler1999] a change made to the internal structure of
                             software to make it easier to understand and cheaper to
                             modify without changing its observable behaviour
                           – [Roberts1998] A behaviour-preserving source-to-source
                             program transformation
                           – [Beck1999] A change to the system that leaves its
                             behaviour unchanged, but enhances some non-functional
                             quality - simplicity, flexibility, understandability, ...
       8
                                          Motivating example
                                           Encapsulate Field
                                          Fowler 1999, page 206
                                             There is a public field
                                        Make it private and provide accessors
Tom Mens, UMH, 2005
                              Rectangle        Rectangle
                                                                    Point    Point
                             length           upperLeft
                             width            lowerRight        x           r
                             origin                             y           theta
                                              area
                             area             circumference     movex:y:    movex:y:
                             circumference    moveTo:
                             moveTo:
    11
                      Motivating example
Tom Mens, UMH, 2005
                       Encapsulate Field
    12
                      Motivating example
Tom Mens, UMH, 2005
                       Encapsulate Field
    13
                                Why do we need refactoring?
                           – software complexity
                           – software maintenance costs
                      •   To increase
                           – software understandibility
                             • e.g., by introducing design patterns
                           – software productivity
                             • at long term, not at short term
                      •To facilitate future changes
                      •…
    14
                                When do we need to refactor?
                                                                 Iterative development
                           – expansion
                                                                         New / Changing
                              • adding new functionality                  Requirements
                           – consolidation
                                                           CONSOLI-
                              • reorganise and restructure DATION                        EXPANSION
                                the software to make it more
                                reusable and easier to maintain
                                                                             More
                              • introduce design patterns                    Reuse
                              • apply refactorings
                                                            Consolidation is necessary to ensure next
                                                                       expansion success
    16
                                When do we need to refactor?
                                      Some guidelines
    17
                             How do we know what to refactor?
                      •   Examples
                           – Duplicated Code
                           – Long Method
                              • The longer the method the harder it is to see what it’s doing
                           – Large Class
                           – Case Statement
                              • replace procedural code by object-oriented code
                           – Feature Envy
                              • Often a method that seems more interested in a class other
                                than the one it's actually in.
                           – Lazy Class
    18                     – ...
                             How do we know what to refactor?
                      Bad smell         Proposed refactoring
                      duplicated code   extract method
                                        pull up variable
                                        form template method
Tom Mens, UMH, 2005
substitute algorithm
                           – Mac OS X
                           – Linux
    21
                                       Refactoring tool support
                              • RefactorIT
                           – Oracle Jdeveloper
                              • RefactorIT
                           – Borland JBuilder
                              • RefactorIT
                           – Eclipse
                              • built-in
                           – IntelliJ IDEA
                              • built-in
                           – Emacs
                              • Xrefactory
                           – Visual Studio .NET
                              • C# Refactory
    22
                                      Refactoring tool support
• Current limitations
                              • class refactorings
                                  – add (sub)class to hierarchy, rename class, remove class
                              • method refactorings
                                  – add to class, rename, remove, push down, pull up, add
                                    parameter, move to component, extract code
                              • variable refactorings
                                  – add to class, rename, remove, push down, pull up, create
                                    accessors, abstract variable
                           – no support for high-level refactorings
    23
                        Refactoring tool support
Tom Mens, UMH, 2005
                      Smalltalk - refactoring browser
    24
                       Refactoring tool support
Tom Mens, UMH, 2005
                      Eclipse - Java refactoring
    25
categories of refactoring
                            categories of refactoring techniques
    27
                                   categories of refactoring
                                     according to Demeyer
[Demeyer&al 2000]
    28
                                    categories of refactoring
                                 1. Creating template methods
                      B              C           D               B              C                D
           m{…            …}   m{…        …}                n{       }   n{      ;super.n }
    29
                                   categories of refactoring
                                   2.a Refactor to specialise
                      •   Refactor to specialise
                           – improve class hierarchy structure by decomposing
                             a large, complex class into several smaller classes
Tom Mens, UMH, 2005
    30
                                        categories of refactoring
                                        2.a Refactor to specialise
                                     copyDisk                                     Disk
                                    formatDisk                                     ...
                                        ...                                     copyDisk
                                                                               formatDisk
                                                                                   ...
    31
                                   categories of refactoring
                                   2.b Refactor to generalise
                      •   Refactor to generalise
                          – identify proper abstractions by examining
                            concrete examples and generalising their
Tom Mens, UMH, 2005
                            commonalities
                          – e.g. abstract classes can be generalised from
                            concrete ones using bottom up analysis of the
                            class hierarchy
                      •   Example
Tom Mens, UMH, 2005
                                                         OutputServer
                            PrintServer
                                                         output
                            print:Boolean
save
    33
                                  categories of refactoring
                                  2.b Refactor to generalise
    34
                                   categories of refactoring
                          3. Incorporating composition relationships
                      •   Motivation
                          – Inheritance is sometimes overused and incorrectly used in
                            modelling the relationships among classes
                          – Aggregations are another way to model these relationships
Tom Mens, UMH, 2005
    35
                                    categories of refactoring
                            3. Incorporating composition relationships
                      •   Example
                           – Convert inheritance into aggregation
Tom Mens, UMH, 2005
output
    36
                                        categories of refactoring
                                           according to Fowler
                      •   small refactorings
                           –   (de)composing methods [9 refactorings]
                           –   moving features between objects [8 refactorings]
                           –   organising data [16 refactorings]
Tom Mens, UMH, 2005
    37
                                   categories of refactoring
                                      small refactorings
                      •   small refactorings
                          – (de)composing methods [9 refactorings]
                             •   Extract Method
Tom Mens, UMH, 2005
                             •   Inline Method
                             •   Inline Temp
                             •   Replace Temp With Query
                             •   Introduce Explaining Variable
                             •   Split Temporary Variable
                             •   Remove Assignments to Parameter
                             •   Replace Method With Method Object
                             •   Substitute Algorithm
    38
                                         categories of refactoring
                                            small refactorings
                      •   (de)composing methods
                            – Extract Method
Tom Mens, UMH, 2005
    39
                                        categories of refactoring
                                           small refactorings
                      •   (de)composing methods
                           – Inline Method (opposite of Extract Method)
Tom Mens, UMH, 2005
    40
                                       categories of refactoring
                                          small refactorings
                      •   (de)composing methods
                           – Inline Temp
Tom Mens, UMH, 2005
    41
                                          categories of refactoring
                                             small refactorings
                      •   (de)composing methods
                           – Replace Temp With Query
Tom Mens, UMH, 2005
    42
                                          categories of refactoring
                                             small refactorings
                      •   (de)composing methods
                           – Introduce Explaining Variable
Tom Mens, UMH, 2005
    43
                                         categories of refactoring
                                            small refactorings
                      •   (de)composing methods
                           – Split Temporary Variable
Tom Mens, UMH, 2005
    44
                                            categories of refactoring
                                               small refactorings
                      •   (de)composing methods
                           – Remove Assignments To Parameter
Tom Mens, UMH, 2005
    45
                                      categories of refactoring
                                         small refactorings
                      •   (de)composing methods
                           – Replace Method With Method Object
Tom Mens, UMH, 2005
    46
                                               categories of refactoring
                                                  small refactorings
                      •   (de)composing methods
                           – Substitute Algorithm
Tom Mens, UMH, 2005
    47
                                     categories of refactoring
                                        small refactorings
                      •   small refactorings
                           – moving features between objects [8 refactorings]
                             •   Move Method
Tom Mens, UMH, 2005
                             •   Move Field
                             •   Extract Class
                             •   Inline Class
                             •   Hide Delegate
                             •   Remove Middle Man
                             •   Introduce Foreign Method
                             •   Introduce Local Extension
    48
                                   categories of refactoring
                                      small refactorings
                               aMethod()
                                                                         aMethod()
    49
                                       categories of refactoring
                                          small refactorings
                          what: when you have a class doing work that should be done
                          by
                                two, create a new class and move the relevant fields and
                                methods to the new class
                          why: large classes are hard to understand
                          example:
                           Person
                          what: when you have a class that does not do very much, move
                                all its features into another class and delete it
                          why: to remove useless classes (as a result of other refactorings)
                          example:
                                            officePhone
    51
                                        categories of refactoring
                                           small refactorings
    52
                                      categories of refactoring
                                         small refactorings
                                                            Person            Department
                                             Department
                                                            getDepartment()   getManager()
    53
                                         categories of refactoring
                                            small refactorings
    54
                                       categories of refactoring
                                          small refactorings
    55
                                     categories of refactoring
                                        small refactorings
                      •   small refactorings
                           – organising data [16 refactorings]
                             •   encapsulate field (see motivating example)
Tom Mens, UMH, 2005
                      •   organising data
                           – Encapsulate field
Tom Mens, UMH, 2005
                          what:
                          why:
                          example:
                                                    private String name;
                          public String name;       public String getName() {
                                                      return this.name; }
                                                    public void setName(String s) {
                                                      this.name = s; }
    57
                                        categories of refactoring
                                           small refactorings
                      •   organising data
                           – Replace data value with object
Tom Mens, UMH, 2005
what:
                          why:
                                                                private Document doc;
                          example:                              public String getContents() {
                                                                  return this.doc.contents; }
                          private String contents;              public void setContents(String s) {
                          public String getContents() {           this.doc.contents = s; }
                            return this.contents; }
                          public void setContents(String s) {   public class Document {
                            this.contents = s; }                  ...
                                                                  public String contents;
                                                                }
    58
                                    categories of refactoring
                                       small refactorings
                      •   organising data
                           – Replace type code with subclasses
Tom Mens, UMH, 2005
                                   Employee                            Employee
                                   const Engineer=0
                                   const Salesman=1
                                   const Manager=2
                                   type:Int
                                                            Engineer   Salesman Manager
    59
                                      categories of refactoring
                                         small refactorings
                      •   organising data
                           – Replace type code with state/strategy
                             • if subclassing cannot be used, e.g., because of dynamic
Tom Mens, UMH, 2005
                      •   organising data
                           – Replace subclass with fields
Tom Mens, UMH, 2005
Male Female
                      •   small refactorings
                           – simplifying conditional expressions [8
                             refactorings]
Tom Mens, UMH, 2005
                             •   decompose conditional
                             •   consolidate conditional expression
                             •   consolidate duplicate conditional fragments
                             •   remove control flag
                             •   replace nested conditional with guard clauses
                             •   replace conditional with polymorphism
                             •   introduce null objects
                             •   introduce assertion
    62
                                     categories of refactoring
                                        small refactorings
                      •   small refactorings
                           – dealing with generalisation [12 refactorings]
                             •   push down method / field
Tom Mens, UMH, 2005
    63
                                         categories of refactoring
                                            small refactorings
Printserver Printserver
                                                        ASCIIPrinter        PSPrinter
                          ASCIIPrinter    PSPrinter     print               print
    64
                                   categories of refactoring
                                      small refactorings
                      •   Pull Up Method
                           – simplest variant
                             • look for methods with same name in subclasses that do
Tom Mens, UMH, 2005
    65
                                      categories of refactoring
                                         small refactorings
Printserver Printserver
accept
ASCIIPrinter PSPrinter
    66
                                     categories of refactoring
                                        small refactorings
Outputserver
    67
                                       categories of refactoring
                                          small refactorings
                      •   small refactorings
                           – simplifying method calls [15 refactorings]
                              •   rename method
Tom Mens, UMH, 2005
                              •   add/remove parameter
                              •   separate query from modifier
                              •   parameterize method
                              •   replace parameter with method
                              •   preserve whole object
                              •   introduce parameter object
                              •   remove setting method
                              •   hide method
                              •   replace constructor with factory method
                              •   encapsulate downcast
                              •   replace error code with exception
                              •   replace exception with test
    68
                                     categories of refactoring
                                        small refactorings
object
                                  Customer                             Customer
                      amountInvoicedIn(from:Date,to:Date)     amountInvoicedIn(r:DateRange)
                      amountReceivedIn(from:Date,to:Date)     amountReceivedIn(r:DateRange)
                      amountOverdueIn(from:Date,to:Date)      amountOverdueIn(r:DateRange)
    69
                                         categories of refactoring
                                            small refactorings
    70
                                   categories of refactoring
                                       big refactorings
                      •   characteristics
                           – require a large amount of time (> 1 month)
                           – require a degree of agreement among the
Tom Mens, UMH, 2005
                             development team
                           – no instant satisfaction, no visible progress
                      •   different kinds
                           – tease apart inheritance
                           – extract hierarchy
                           – convert procedural design into objects
                           – separate domain from presentation
    71
                                     categories of refactoring
                                         big refactorings
                      •   Solution
                           – create 2 separate hierarchies and use delegation to invoke
                             one from the other
                      •   Approach
                           – identify the different jobs done by the hierarchy
                           – extract least important job into a separate hierarchy
                              • use extract class to create common parent of new hierarchy
                              • create appropriate subclasses
                              • use move method to move part of the behaviour from the old
                                hierarchy to the new one
                              • eliminate unnecessary (empty) subclasses in original hierarchy
                              • apply further refactorings (e.g. pull up method/field)
    72
                                       categories of refactoring
                                           big refactorings
                                    Window
Tom Mens, UMH, 2005
                                                                                 1
                                                                    WindowImpl          Window
                             Full                Iconised
                      Extract hierarchy
                      • Problem
                           – an overly-complex class that is doing too much work, at
Tom Mens, UMH, 2005
                      Extract hierarchy
                      • Example
                        – calculating electricity bills
Tom Mens, UMH, 2005
    75
                                   categories of refactoring
                                       big refactorings
                      •   Solution
                           – turn the data records into objects, break up the
                             behaviour, and move the behaviour to the objects
                      •   Used small refactorings
                           – extract method
                           – move method
                           –…
    76
                                   categories of refactoring
                                       big refactorings
    80
                           refactoring of UML activity diagrams
    81
                      refactoring of UML activity diagrams
Tom Mens, UMH, 2005
                            Make Actions Concurrent
82