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

Slides:



Advertisements
Similar presentations
12-Dec-14 Refactoring IV. Previously discussed bad smells Duplicated code — and other forms of redundancy Long method — use short methods that delegate.
Advertisements

© 2010 Shawn A. Bohner Software Construction and Evolution - CSSE 375 Even more Bad Smells in Code Shawn & Steve Q1 Shawn & Steve Hint 
1 Software Maintenance and Evolution CSSE 575: Session 2, Part 2 Composing Methods Steve Chenoweth Office Phone: (812) Cell: (937)
Refactoring and Code Smells
Refactoring Overview  What is refactoring?  What are four good reasons to refactor?  When should you refactor?  What is a bad smell (relative to refactoring.
Software Construction and Evolution - CSSE 375 Bad Smells in Code Shawn Bohner & Steve Chenoweth.
1 Software Maintenance and Evolution CSSE 575: Session 3, Part 4 Big Refactorings Steve Chenoweth Office Phone: (812) Cell: (937)
1 Software Maintenance and Evolution CSSE 575: Session 1, Part 4 Even more Bad Smells in Code Steve Chenoweth Office Phone: (812) Cell: (937)
George Blank University Lecturer. REFACTORING Improving the Design of Existing Code Supplement to Ian Sommerville, Software Engineering, Chapter 20 Prepared.
25-Jun-15 Refactoring III. General philosophy A refactoring is just a way of rearranging code Refactorings are used to solve problems If there’s no problem,
REFACTORING Improving the Design of Existing Code Atakan Şimşek e
Maintenance Refactoring and Code Smells. Where are we? Over the semester we have talked about Software Engineering. The overall goal of software engineering.
Refactoring – III Measured Smells. Smells Covered 1. Comments 2. Long method 3. Large Class 462.
Refactoring Cristescu Marilena. Definitions Loose Usage: Reorganize a program(or something) As a noun: a change made to the internal structure of some.
Refactoring. Refactoring is a step in the software design process.
1 Software Maintenance and Evolution CSSE 575: Session 1, Part 3 Bad Smells in Code - 1 Steve Chenoweth Office Phone: (812) Cell: (937)
Refactoring. Mathematics: Factor ● fac·tor – One of two or more quantities that divides a given quantity without a remainder, e.g., 2 and 3 are factors.
Refactoring - A disciplined approach to rework for better design.
Refactoring Improving the structure of existing code Refactoring1.
Small changes to code to improve it. Refactoring Defined A change made to the internal structure of software to make it easier to understand and cheaper.
Refactoring (continued) Source: "Refactoring: Improving the Design of Existing Code", Martin Fowler.
SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.
When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation Senior Developer and Team Leader.
Best Practices. Contents Bad Practices Good Practices.
Refactoring1 Improving the structure of existing code.
Refactoring Deciding what to make a superclass or interface is difficult. Some of these refactorings are helpful. Some research items include Inheritance.
Introduction to Refactoring Jim Cooper Falafel Software.
Informatics 122 Software Design II
Incremental Design Why incremental design? Goal of incremental design Tools for incremental design  UML diagrams  Design principles  Design patterns.
Software Engineering CS3003 Lecture 4 Code bad smells and refactoring.
Refactoring and such ● (Side note) Specialization ● Key terms ● Abstraction, state, persistence and association and their relationship to software development.
Refactoring: Code Smells. Admin Notes REGISTER FOR BLACKBOARD Watch blackboard site for updates on class as hurricane season approaches.
Refactoring. Refactoring Overview  What is refactoring?  What are four good reasons to refactor?  When should you refactor?  What is a bad smell (relative.
Refactoring 2. Admin Blackboard Quiz Acknowledgements Material in this presentation was drawn from Martin Fowler, Refactoring: Improving the Design of.
REFACTORINGREFACTORING. Realities Code evolves substantially during development Requirements changes 1%-4% per month on a project Current methodologies.
NJIT 1 Test Driven Development and Refactoring Larman, Chapter 21.
Refactoring II Dealing with Polymorphism. Switch in Rental Switches on Movie! class Rental … public double getCharge() { double result = 0; switch (getMovie().getPriceCode()){
Module 3. Smells Between Classes Course: Refactoring.
1 Software Maintenance and Evolution CSSE 575: Session 2, Part 1 Refactoring Principles Steve Chenoweth Office Phone: (812) Cell: (937)
1 Software Maintenance and Evolution CSSE 575: Session 3, Part 3 Dealing with Generalization Steve Chenoweth Office Phone: (812) Cell: (937)
SEG 4110 – Advanced Software Design and Reengineering Topic T Introduction to Refactoring.
Refactoring Advanced Software Engineering Dr Nuha El-Khalili.
Refactoring. Mathematics: Factor ● fac·tor – One of two or more quantities that divides a given quantity without a remainder, e.g., 2 and 3 are factors.
Refactoring1 Improving the structure of existing code.
Pertemuan 12 Refactoring Mata kuliah: T0144 – Advanced Topics in Software Engineering Tahun: 2010.
Refactoring. 2 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.
CSSE 375 Organizing Data – Part 1 Shawn and Steve Q1.
Software Construction and Evolution - CSSE 375 Dealing with Generalization Steve and Shawn Left – In the 1990 movie “The Freshman,” Matthew Broderick,
Refactoring. DCS – SWC 2 Refactoring ”A change made to the internal structure of software to make it easier to understand and cheaper to modify without.
Module 9. Dealing with Generalization Course: Refactoring.
Catalog of Refactoring (1) Composing Methods. Code Smells Long methods Dubious temporary variables Dubious methods.
ICONFINDER ICONFINDER Founded Django based web application -PostgreSQL -Elasticsearch -Amazon Elastic Compute.
A (Very) Simple Example Consolidate duplicate conditional fragments if (isSpecialDeal()) { total = price * 0.95; send (); } else { total = price * 0.98;
Principles and examples
Steve Chenoweth Office Phone: (812) Cell: (937)
Module Road Map Refactoring Why Refactoring? Examples
Steve Chenoweth Office Phone: (812) Cell: (937)
Refactoring and Code Smells
Software Construction and Evolution - CSSE 375 Composing Methods
Refactoring III 27-Nov-18.
Code Smells 1.
Improving the structure of existing code
Refactoring and Code Smells
Refactoring III 25-Dec-18.
Refactoring.
Refactoring and Code Smells
Refactoring and Code Smells
Refactoring.
Refactoring and Code Smells
Presentation transcript:

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

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

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.

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

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.

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.

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.

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.

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…

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.

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

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

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.

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.

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.

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.

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.

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

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

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

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); }

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); }

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

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); }

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);}

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

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);}

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; }

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!