Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Refactoring Excerpted from ‘What is Refactoring?’ by William C. Wake and Refactoring: Improving the Design of Existing Code by Martin Fowler.

Similar presentations


Presentation on theme: "Introduction to Refactoring Excerpted from ‘What is Refactoring?’ by William C. Wake and Refactoring: Improving the Design of Existing Code by Martin Fowler."— Presentation transcript:

1 Introduction to Refactoring Excerpted from ‘What is Refactoring?’ by William C. Wake and Refactoring: Improving the Design of Existing Code by Martin Fowler

2 Outline What is Refactoring? What is Refactoring? Why Refactor? Why Refactor? When to Refactor? When to Refactor? Why Refactoring Works? Why Refactoring Works? Bad Smells Bad Smells Types of Refactorings Types of Refactorings

3 What is Refactoring? The process of improving the design of code without affecting its external behavior. The process of improving the design of code without affecting its external behavior. Refactor to keep your code as simple as possible. Refactor to keep your code as simple as possible. Refactored code is clearer, simpler and of higher quality. Refactored code is clearer, simpler and of higher quality. Refactoring is not performance optimization. Refactoring is not performance optimization.

4 What is Refactoring? (cont…) Side Effects Side Effects Often, code size is reduced Often, code size is reduced Confusing structures are transformed into simpler constructs Confusing structures are transformed into simpler constructs Lessons Learned Lessons Learned Management buy-in is necessary Management buy-in is necessary Must follow systematic approach to refactoring Must follow systematic approach to refactoring

5 Why Refactor? Refactor to improve the design of software. Refactor to improve the design of software. Refactoring can “tidy up” sloppy code. Refactoring can “tidy up” sloppy code. Reducing the amount of code can make future modifications easier. Reducing the amount of code can make future modifications easier. Refactoring makes code easier to understand. Refactoring makes code easier to understand. Refactoring helps you find bugs. Refactoring helps you find bugs. Refactoring helps you program faster. Refactoring helps you program faster.

6 When to Refactor? Refactoring is something you do all the time in small bursts. Refactoring is something you do all the time in small bursts. The Rule of Three – Three strikes, you refactor. The Rule of Three – Three strikes, you refactor. Refactor when you add features. Refactor when you add features. Refactor when you need to fix a bug. Refactor when you need to fix a bug. Refactor as you do a code review. Refactor as you do a code review.

7 Why Refactoring Works Programs that are hard to read are hard to modify. Programs that are hard to read are hard to modify. Programs that have duplicated logic are hard to modify. Programs that have duplicated logic are hard to modify. Programs that require additional behavior that requires you to change running code are hard to modify. Programs that require additional behavior that requires you to change running code are hard to modify. Programs with complex conditional logic are hard to modify. Programs with complex conditional logic are hard to modify.

8 Bad Smells Duplicate Code Duplicate Code Long Method Long Method Large Class Large Class Long Parameter List Long Parameter List Divergent Change – one type of change requires changing one subset of modules; another type of change requires changing another. Divergent Change – one type of change requires changing one subset of modules; another type of change requires changing another. Shotgun Surgery – the opposite of divergent change, a change requires a lot of little changes to a lot of different classes. Shotgun Surgery – the opposite of divergent change, a change requires a lot of little changes to a lot of different classes. Feature Envy – a method in a class seems to not belong. Feature Envy – a method in a class seems to not belong. Data Clumps –member fields that clump together but are not part of the same class Data Clumps –member fields that clump together but are not part of the same class Primitive Obsession – characterized by the use of primitives in place of class methods. Primitive Obsession – characterized by the use of primitives in place of class methods.

9 Bad Smells (cont…) Switch Statements – often duplicated code that can be replaced by polymorphism. Switch Statements – often duplicated code that can be replaced by polymorphism. Parallel Inheritance Hierarchies – duplicated code in subclasses that share a common ancestor. Parallel Inheritance Hierarchies – duplicated code in subclasses that share a common ancestor. Lazy Class – a class that has little meaning in the of the software. Lazy Class – a class that has little meaning in the of the software. Speculative Generality – methods (often stubs) that are placeholders for future features. Speculative Generality – methods (often stubs) that are placeholders for future features. Temporary Field – a member variable that is only used under certain circumstances. Temporary Field – a member variable that is only used under certain circumstances. Message Chains – object that requests an object for another object which asks… Message Chains – object that requests an object for another object which asks…

10 Bad Smells (cont…) Middle Man – a class that is just a “pass-through” method with little logic. Middle Man – a class that is just a “pass-through” method with little logic. Inappropriate Intimacy – violation of private parts. Inappropriate Intimacy – violation of private parts. Alternate Class with Different Interfaces - two methods that do the same thing, but have different interfaces. Alternate Class with Different Interfaces - two methods that do the same thing, but have different interfaces. Incomplete Library Classes – a framework that doesn’t do everything you need. Incomplete Library Classes – a framework that doesn’t do everything you need. Data Class – classes that have getters and setters, but no real function. Data Class – classes that have getters and setters, but no real function. Refused Bequest – a subclass that over-rides most of the functionality provided by its superclass. Refused Bequest – a subclass that over-rides most of the functionality provided by its superclass. Comments – text that explains bad code. Comments – text that explains bad code.

11 Types of Refactorings Moving Features Between Objects Moving Features Between Objects Goal: ensure tight cohesion Goal: ensure tight cohesion Organizing Data Organizing Data Goal: encapsulate data appropriately Goal: encapsulate data appropriately Simplifying Conditional Expressions Simplifying Conditional Expressions Goal: unclutter decision points Goal: unclutter decision points Making Method Calls Simpler Making Method Calls Simpler Goal: user parameterization sensibly Goal: user parameterization sensibly Dealing With Generalization Dealing With Generalization Goal: use inheritance structure properly Goal: use inheritance structure properly Big Refactorings Big Refactorings Goal: re-architect if necessary Goal: re-architect if necessary Composing Methods Composing Methods Goal: ensure loose coupling Goal: ensure loose coupling

12 Moving Features Between Objects Extract Class Extract Class You have one class doing work that should be done by two. You have one class doing work that should be done by two. Create a new class and move the relevant fields and methods from the old class into the new class. Create a new class and move the relevant fields and methods from the old class into the new class. Smells Smells Large Class, Data Clumps Large Class, Data Clumps

13 Organizing Data Replace Magic Number with Symbolic Constant Replace Magic Number with Symbolic Constant You have a literal number with a particular meaning You have a literal number with a particular meaning Create a constant, name it after the meaning, and replace the number with it. Create a constant, name it after the meaning, and replace the number with it.

14 Simplifying Conditional Expressions Decompose Conditional Decompose Conditional You have a complicated conditional (if-then-else) statement. You have a complicated conditional (if-then-else) statement. Extract methods from the condition, then part, and else parts. Extract methods from the condition, then part, and else parts.

15 Making Method Calls Simpler Rename Method Rename Method The name of a method does not reveal its purpose. The name of a method does not reveal its purpose. Change the name of the method. Change the name of the method.

16 Dealing with Generalization Extract Subclass Extract Subclass A class has features that are used only in some instances. A class has features that are used only in some instances. Create a subclass for that subset of features. Create a subclass for that subset of features.

17 Big Refactorings Convert Procedural Design to Objects Convert Procedural Design to Objects You have code written in a procedural style You have code written in a procedural style Turn the data records into objects, break up the behavior, and move the behavior to the objects. Turn the data records into objects, break up the behavior, and move the behavior to the objects.

18 Composing Methods Extract Method Extract Method You have a code fragment that can be grouped together You have a code fragment that can be grouped together Turn the fragment into a method whose name explains the purpose of the method. Turn the fragment into a method whose name explains the purpose of the method. Smells Smells Large Method Large Method Comments Comments

19 Extract Method Mechanics Mechanics create new method create new method name by what it does, not how it does it name by what it does, not how it does it rule of thumb: if you can’t come up with a meaningful name, then don’t extract rule of thumb: if you can’t come up with a meaningful name, then don’t extract copy extracted code from source to target copy extracted code from source to target locate variables used in target but defined in source scope. Choices: locate variables used in target but defined in source scope. Choices: if modified by target, consider method as a query if modified by target, consider method as a query make variables params to method make variables params to method if can be used only in extracted code, make temps if can be used only in extracted code, make temps compile (and test, as appropriate) compile (and test, as appropriate) replace extracted code in source with call replace extracted code in source with call remove extraneous variables remove extraneous variables compile and test compile and test

20 Extract Method (cont…) void printOwing() { Enumeration e = _order.elements(); double outstanding = 0.0; System.out.println (“******************************”); System.out.println (“***** Customer Owes *****”); System.out.println (“******************************”); while (e.hasMoreElements()) { Order each (Order) e.nextElement(); outstanding += each.getAmount(); } System.out.println(“name: “ + _name); System.out.println(“amount “ + outstanding); } “Islands” of abstraction

21 Extract Method (cont…) void printOwing() { Enumeration e = _order.elements(); double outstanding = 0.0; System.out.println (“******************************”); System.out.println (“***** Customer Owes *****”); System.out.println (“******************************”); while (e.hasMoreElements()) { Order each (Order) e.nextElement(); outstanding += each.getAmount(); } System.out.println(“name: “ + _name); System.out.println(“amount “ + outstanding); }

22 Extract Method (cont…) void printOwing() { Enumeration e = _order.elements(); double outstanding = 0.0; printBanner(); printBanner(); while (e.hasMoreElements()) { Order each (Order) e.nextElement(); outstanding += each.getAmount(); } System.out.println(“name: “ + _name); System.out.println(“amount “ + outstanding); }

23 Extract Method (cont…) void printBanner() { System.out.println (“******************************”); System.out.println (“***** Customer Owes *****”); System.out.println (“******************************”); }

24 Extract Method (cont…) void printOwing() { Enumeration e = _order.elements(); double outstanding = 0.0; printBanner(); printBanner(); while (e.hasMoreElements()) { Order each (Order) e.nextElement(); outstanding += each.getAmount(); } System.out.println(“name: “ + _name); System.out.println(“amount “ + outstanding); }

25 Extract Method (cont…) void printOwing() { Enumeration e = _order.elements(); double outstanding = 0.0; printBanner(); printBanner(); while (e.hasMoreElements()) { Order each (Order) e.nextElement(); outstanding += each.getAmount(); } printDetails(outstanding); printDetails(outstanding);}

26 Extract Method (cont…) void printDetails(double outstanding) { System.out.println(“name: “ + _name); System.out.println(“amount “ + outstanding); }

27 Extract Method (cont…) void printOwing() { Enumeration e = _order.elements(); double outstanding = 0.0; printBanner(); printBanner(); while (e.hasMoreElements()) { Order each (Order) e.nextElement(); outstanding += each.getAmount(); } printDetails(outstanding); printDetails(outstanding);}

28 Extract Method (cont…) void printOwing() {printBanner(); double outstanding = getOutstanding(); printDetails(outstanding);} void getOutstanding() { Enumeration e = _order.elements(); double result = 0.0; while (e.hasMoreElements()) { Order each (Order) e.nextElement(); result += each.getAmount(); } return result; }

29 Summary Most code should be human-readable first, machine readable second. Most code should be human-readable first, machine readable second. Refactoring improves code comprehension, thus making maintenance easier. Refactoring improves code comprehension, thus making maintenance easier. Although identifying what to refactor is an art, the process of refactoring is very algorithmic. Although identifying what to refactor is an art, the process of refactoring is very algorithmic. ALWAYS, ALWAYS TEST YOUR CODE BEFORE AND AFTER YOU REFACTOR! ALWAYS, ALWAYS TEST YOUR CODE BEFORE AND AFTER YOU REFACTOR!


Download ppt "Introduction to Refactoring Excerpted from ‘What is Refactoring?’ by William C. Wake and Refactoring: Improving the Design of Existing Code by Martin Fowler."

Similar presentations


Ads by Google