Refactoring II 5-Feb-19.

Slides:



Advertisements
Similar presentations
Test-Driven Development and Refactoring CPSC 315 – Programming Studio.
Advertisements

Refactoring Overview  What is refactoring?  What are four good reasons to refactor?  When should you refactor?  What is a bad smell (relative to refactoring.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
13-Jul-15 Refactoring II. Books Design Patterns is the classic book by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides Basically a catalog.
Refactoring to Patterns Ravindra Chilaka Extreme Programming Seminar XP 2004 b.
15-Aug-15 Design Patterns and Refactoring. 2 History A Pattern Language: Towns, Buildings, Construction, Christopher Alexander, 1977 The Timeless Way.
21-Aug-15 Design Patterns and Refactoring. 2 History A Pattern Language: Towns, Buildings, Construction, Christopher Alexander, 1977 The Timeless Way.
JUnit The framework. Goal of the presentation showing the design and construction of JUnit, a piece of software with proven value.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Software Refactoring Part I: Introduction Bartosz Walter Advanced Object-Oriented Design Lecture 5.
Sadegh Aliakbary Sharif University of Technology Spring 2012.
SOFTWARE DESIGN AND ARCHITECTURE LECTURE 27. Review UML dynamic view – State Diagrams.
Software Engineering 1 Object-oriented Analysis and Design Chap 21 Test-Driven Development and Refactoring.
Refactoring Improving the structure of existing code Refactoring1.
17-Oct-15 Refactoring. 2 Refactoring is: restructuring (rearranging) code......in a series of small, semantics-preserving transformations (i.e. the code.
17-Oct-15 Design Patterns and Refactoring CSC 2053.
Refactoring1 Improving the structure of existing code.
L11-12: Design Patterns Definition Iterator (L4: Inheritance)‏ Factory (L4: Inheritance)‏ Strategy (L5: Multiple Inheritance)‏ Composite (L6: Implementation.
31-Oct-15 Simple UML IB Computer Science. 2 What is UML? UML stands for Unified Modeling Language UML is a diagramming language designed for Object- Oriented.
Refactoring Deciding what to make a superclass or interface is difficult. Some of these refactorings are helpful. Some research items include Inheritance.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Unit Testing with JUnit and Clover Based on material from: Daniel Amyot JUnit Web site.
1 CSC/ECE 517 Fall 2010 Lec. 3 Overview of Eclipse Lectures Lecture 2 “Lecture 0” Lecture 3 1.Overview 2.Installing and Running 3.Building and Running.
Software Engineering CS3003 Lecture 4 Code bad smells and refactoring.
Refactoring. Refactoring Overview  What is refactoring?  What are four good reasons to refactor?  When should you refactor?  What is a bad smell (relative.
Chapter 21 Test-Driven Development 1CS6359 Fall 2011 John Cole.
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.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
1 Software Maintenance and Evolution CSSE 575: Session 3, Part 3 Dealing with Generalization Steve Chenoweth Office Phone: (812) Cell: (937)
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Refactoring1 Improving the structure of existing code.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
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.
Class Relationships Lecture Oo08 Polymorphism. References n Booch, et al, The Unified Modeling Language User Guide, Chapt 10 p.125 n Fowler & Scott, UML.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
Software Engineering 1 Object-oriented Analysis and Design Applying UML and Patterns An Introduction to Object-oriented Analysis and Design and Iterative.
Design Patterns: MORE Examples
Module Road Map Refactoring Why Refactoring? Examples
Lecture 12 Inheritance.
MPCS – Advanced java Programming
Low Budget Productions, LLC
Pertemuan 08 Design Patterns & Anti-Patterns
Behavioral Design Patterns
Object-Oriented Programming
Chapter 3 Inheritance © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Refactoring II 21-Sep-18.
Simple UML 11-Nov-18.
بازآرایی برنامه Code Refactoring
Overview of Eclipse Lectures
08/15/09 Design Patterns James Brucker.
Simple UML 7-Dec-18.
Advanced Java Programming
Improving the structure of existing code
Advanced Programming Behnam Hatami Fall 2017.
Informatics 122 Software Design II
Controlling Program Flow
Refactoring.
Presentation transcript:

Refactoring II 5-Feb-19

Books I Design Patterns is the classic book by “the Gang of Four”: Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides Basically a catalog of program organizations Reading it is rather like reading a dictionary Although equally applicable to Java, the examples are in C++ Head First Design Patterns by Elizabeth Freeman Fun, irreverent, and entertaining IMHO the best book for developing an understanding of what design patterns are all about

Books II AntiPatterns: Refactoring Software, Architectures, and Projects in Crisis by William J. Brown, Raphael C. Malveau, Hays W. "Skip" McCormick, Thomas J. Mowbray Describes bad patterns and how to fix them More fun to read than the Gang of Four book Refactoring: Improving the Design of Existing Code by Martin Fowler, with contributions from Kent Beck and others Very clear, plenty of useful ideas, very readable Much of this lecture will be based on this book

Design Patterns and Refactoring Design Patterns describe good solutions to common (or at least, not extremely rare) design problems Design Patterns are always specified in UML Model-View-Controller is a very common Design Pattern An Antipattern is a common, but poor, Design Pattern Antipatterns can be refactored into better designs Refactoring is rearranging existing code while maintaining the same functionality Refactoring is usually done in terms of applying some Design Pattern

UML review I Key: Example: Name of the class Variables [optional] Card cardId:int -copy:boolean=false «constructor» Card(int id) +isKind(desiredKind:int) +isSharable():boolean +toString():String Example: Name of the class Variables [optional] Methods Key: + means public visibility # means protected visibility - means private visibility <blank> means default (package) visibility static variables are underlined

UML review II A B A B C D Factory Product creates 1..4 Class B extends class A A B Class B implements interface A C D 1..4 Class C contains 1 to 4 objects of class D Factory Product creates Other kinds of relations

Bad smells Where did this term come from? “If it stinks, change it.” --Grandma Beck, discussing child-rearing philosophy The basic idea is that there are things in code that cause problems Duplicated code Long methods Etc. A common reason for refactoring is that you need to add features that don’t fit well with the existing design Any time you change working code, you run the risk of breaking it A good test suite makes refactoring much easier and safer

An example Some time ago I was working on code to evaluate expressions Expressions can be parsed into a tree structure + 2 * 5 x Tree for 2 + 5 * x Now what? You could walk the tree and, at each node, use a switch statement to do the right thing Adding a new operator requires modifying existing code I “discovered” a better solution Command lhs:Command rhs:Command value:int evaluate():int 0..2

Using my “Command” pattern class Add implements Command { int evaluate( ) { int v1 = lhs.evaluate().value; int v2 = rhs.evaluate().value; value = v1 + v2; return value; } } Command lhs:Command rhs:Command value:int evaluate():int 0..2 To evaluate the entire tree, evaluate the root node To add an operator, add another class that extends Command This is just a rough description; there are a lot of other details to consider Some operands are unary You have to look up the values of variables Etc.

Duplicated code I If the same code fragment occurs in more than one place within a single class, you can use Extract Method Turn the fragment into a method whose name explains the purpose of the method Any local variables that the method requires can be passed as parameters (if there aren’t too many of them!) If the method changes a local variable, see whether it makes sense to return that as the value of the method (possibly changing the name of the method to indicate this) If the method changes two or more variables, you need other refactorings to fix this problem

Duplicated code II If the same code fragment occurs in sibling classes, you can use Extract Method in both classes, then use Pull Up Method Use ExtractMethod in each class Be sure the code is identical If necessary, adjust the method signatures to be identical Copy the extracted method to the common superclass Delete one subclass method Compile and test Delete the other subclass method

Duplicated code III If the same code fragment occurs in unrelated classes, you can use Extract Method in one class, then: Use this class as a component in the other class, or Invoke the method from the other class, or Move the method to a third class and refer to it from both of the original classes In any case, you need to decide where the method makes most sense, and put it there Eclipse has an Extract method... command that does most of this work for you

Duplicated code IV If almost the same code fragment occurs in sibling classes, use Extract Method to separate the similar bits from the different bits, and use Form Template Method I’ll give an example in a moment

The Template Method Template Methods lead to an inverted control structure A superclass calls methods in its subclass Template methods are so fundamental that they can be found in almost every abstract class Template Method uses inheritance A similar pattern, Strategy Pattern, uses delegation rather than inheritance

Big fish and little fish The scenario: “big fish” and “little fish” move around in an “ocean” Fish move about randomly A big fish can move to where a little fish is (and eat it) A little fish will not move to where a big fish is Here’s the initial code (before refactoring): BigFish move() <<abstract>>Fish <<abstract>>move() LittleFish

The move() method General outline of the method: public void move() { choose a random direction; // same for both find the location in that direction; // same for both check if it’s ok to move there; // different if it’s ok, make the move; // same for both } To do the Form Template Method: Extract the check on whether it’s ok to move In the Fish class, put the actual (template) move() method Create an abstract okToMove() method in the Fish class Implement okToMove() in each subclass

The Fish refactoring BigFish move() <<abstract>>Fish <<abstract>>move() LittleFish Note how this works: When a BigFish tries to move, it uses the move() method in Fish But the move() method in Fish uses the okToMove(locn) method in BigFish And similarly for LittleFish BigFish okToMove(locn):boolean <<abstract>>Fish move() <<abstract>>okToMove(locn):boolean

The resultant code In Fish: In BigFish and in LittleFish: public void move() { choose a random direction; // same for both find the location in that direction; // same for both check if it’s ok to move there; // same for both if it’s ok, make the move; // same for both } abstract boolean okToMove(locn); In BigFish and in LittleFish: boolean okToMove(locn) { code for this kind of fish }

To be continued...