Catalog of Refactoring

Slides:



Advertisements
Similar presentations
Software Testing and Maintenance 1 Today’s Agenda  Course Evaluation  HW 4 Return  HW 5 Correction  Quiz 4 Next Class  Software Refactoring.
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.
1 Software Maintenance and Evolution CSSE 575: Session 2, Part 3 Moving Features Between Objects Steve Chenoweth Office Phone: (812) Cell: (937)
Introduction to Refactoring Excerpted from ‘What is Refactoring?’ by William C. Wake and Refactoring: Improving the Design of Existing Code by Martin Fowler.
REFACTORING Improving the Design of Existing Code Atakan Şimşek e
Object Oriented Concepts in Java Objects Inheritance Encapsulation Polymorphism.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Refactoring – III Measured Smells. Smells Covered 1. Comments 2. Long method 3. Large Class 462.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Refactoring - A disciplined approach to rework for better design.
Refactoring Improving the structure of existing code Refactoring1.
SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.
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.
Object-Oriented Design CSC 212. Announcements This course is speeding up and we are starting new material. Please see me if you feel this is going too.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
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.
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.
Some Important topics. Working with Files Working with a file involves three steps: – Open the file – Perform operations on the file – Close the file.
Module 3. Smells Between Classes Course: Refactoring.
Classes. Student class We are tasked with creating a class for objects that store data about students. We first want to consider what is needed for the.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
© 2007 Lawrenceville Press Slide 1 Chapter 8 Objects  A variable of a data type that is a class. Also called an instance of a class.  Stores data  Can.
1 Software Maintenance and Evolution CSSE 575: Session 3, Part 3 Dealing with Generalization 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.
CSSE 375 Organizing Data – Part 2 Shawn and Steve Continue the same quiz!
Refactoring1 Improving the structure of existing code.
Refactoring Constants and Variables Lesson Three: Constants and Variables.
CSSE 375 Organizing Data – Part 1 Shawn and Steve Q1.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
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.
Refactoring Refactoring plays a major role in the decisions of where to put responsibilities. While deciding where these responsibilities lie, a refactoring.
Georgia Institute of Technology More on Creating Classes Barb Ericson Georgia Institute of Technology June 2006.
Catalog of Refactoring (1) Composing Methods. Code Smells Long methods Dubious temporary variables Dubious methods.
Catalog of Refactoring (6) Making Method Calls Simpler.
A (Very) Simple Example Consolidate duplicate conditional fragments if (isSpecialDeal()) { total = price * 0.95; send (); } else { total = price * 0.98;
Principles and examples
Catalog of Refactoring
The need for Programming Languages
Classes and Objects: Encapsulation
More Sophisticated Behavior
Module Road Map Refactoring Why Refactoring? Examples
Inheritance and Polymorphism
Refactoring Methods: Kevin Murphy.
Lecture 9-2: Interacting with the Superclass (super);
Phil Tayco Slide version 1.1 Created Oct 30, 2017
Refactoring with inline temp, method, and class
Can perform actions and provide communication
Stacks.
Overview of Eclipse Lectures
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Java Classes and Objects 3rd Lecture
Improving the structure of existing code
Refactoring and Code Smells
Can perform actions and provide communication
Stacks.
Delegation vs inheritance
Refactoring and Code Smells
CIS 199 Final Review.
More on Creating Classes
Building Java Programs
CMPE212 – Reminders Assignment 2 due next Friday.
Software Design Lecture : 28.
Refactoring.
CS 240 – Advanced Programming Concepts
Refactoring and Code Smells
Presentation transcript:

Catalog of Refactoring (2) Moving Features Between Objects

Evolving Software Fundamental decision is where to put responsibility, we won't get it right at the first try Code smell: bloated classes Need moving features between objects

Catalog Move Method Move Field Extract Class Inline Class Hide Delegate Remove Middle Man Introduce Foreign Method Introduce Local Extension

Move Method When a method is, or will be, using or used by more features of another class than the class on which it is defined. Create a new method with a similar body in the class it uses most. Either turn the old method into a simple delegation, or remove it altogether.. Each refactoring method name is written in blue.

Motivation Reduce class bloat Reduce tight coupling between classes Remedy misplaced methods NOTE: if the decision is hard to make, it probably does not matter that much

Mechanics Examine all features used by the source method that are defined on the source class. Check the sub- and superclasses of the source class for other declarations of the method. If there are other declaration, you may not be able to move it Declare the method in the target class. Copy the code from the source method to the target. Adjust the method to make it work in its new home. Compile the target class.

Mechanics Determine how to reference the correct target object from the source. Turn the source method into a delegating method. Compile and test. Decide whether to remove the source method or retain it as a delegating method. If you remove the source method, replace all the references with references to the target method. Compile and test

Move overdraftCharge class Account... double overdraftCharge() { if (_type.isPremium()) { double result = 10; if (_daysOverdrawn > 7) result += (_daysOverdrawn - 7) *0.85; return result; } else return _daysOverdrawn * 1.75; double bankCharge() { double result = 4.5; if (_daysOverdrawn > 0) result += overdraftCharge(); private AccountType _type; private int _daysOverdrawn;

To AccountType class class AccountType... double overdraftCharge(int daysOverdrawn) { if (isPremium()) { double result = 10; if (daysOverdrawn > 7) result += (daysOverdrawn - 7) * 0.85; return result; } else return daysOverdrawn * 1.75; class Account... double overdraftCharge() { return _type.overdraftCharge(_daysOverdrawn);

Move Field A field is, or will be, used by another class more than the class on which it is defined. Create a new field in the target class, and change all its users.

Mechanism If the field is public, encapsulate it Create a field in the target class with getting and setting methods. Compile and test. Determine how to reference the target object from the source. Remove the field on the source class. Replace all references to the source field with references to the appropriate method on the target.

Move _interestRate class Account... private AccountType _type; private double _interestRate; double interestForAmount_days(double amount, int days) { return _interestRate * amount * days / 365; }

To AccountType class class AccountType... private double _interestRate; void setInterestRate (double arg) { _interestRate = arg; } double getInterestRate () { return _interestRate; class Account... double interestForAmount_days (double amount, int days) { return _type.getInterestRate() * amount * days / 365;

Extract Class 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.

Mechanism Decide how to split the responsibilities of the class. Create a new class to express the split-off responsibilities. Make a link from the old to the new class. Use Move Field on each field you wish to move. Use Move Method to move methods over from old to new. Start with lower-level methods (called rather than calling) and build to the higher level. Compile and test after each move. Decide whether to expose the new class. If you do expose the class, decide whether to expose it as a reference object or as an immutable value object.

Example class Person... public String getName() { return _name; } public String getTelephoneNumber() { return ("(" + _officeAreaCode + ") " + _officeNumber); String getOfficeAreaCode() { return _officeAreaCode; void setOfficeAreaCode(String arg) { _officeAreaCode = arg; String getOfficeNumber() { return _officeNumber; void setOfficeNumber(String arg) { _officeNumber = arg; private String _name; private String _officeAreaCode; private String _officeNumber;

Extract TelephoneNumber class class TelephoneNumber... public String getTelephoneNumber() { return ("(" + _areaCode + ") " + _number); } String getAreaCode() { return _areaCode; void setAreaCode(String arg) { _areaCode = arg; String getNumber() { return _number; void setNumber(String arg) { _number = arg; private String _number; private String _areaCode; class Person... private TelephoneNumber _officeTelephone = new TelephoneNumber();

Inline Class A class isn't doing very much. Move all its features into another class and delete it.

Mechanism Declare the public protocol of the source class onto the absorbing class. Delegate all these methods to the source class. Change all references from the source class to the absorbing class. Use Move Method and Move Field to move features from the source class to the Absorbing class until there is nothing left. Compile and test. Delete the source class.

Hide Delegate A client is calling a delegate class of an object. Create methods on the server to hide the delegate.

Motivation If a client calls a method defined on one of the fields of the server object, the client needs to know about this delegate object. If the delegate changes, the client also may have to change. You can remove this dependency by placing a simple delegating method on the server, which hides the delegate

Mechanism For each method on the delegate, create a simple delegating method on the server. Adjust the client to call the server. If no client needs to access the delegate anymore, remove the server's accessor for the delegate. Compile and test after each change.

Example class Person { Department _department; public Department getDepartment() { return _department; } public void setDepartment(Department arg) { _department = arg; class Department { private String _chargeCode; private Person _manager; public Department (Person manager) { _manager = manager; public Person getManager() { return _manager;

Example manager = john.getDepartment().getManager(); public Person getManager() { return _department.getManager(); } manager = john.getManager();

Remove Middle Man Opposite for Hide Delegate A class is doing too much simple delegation. Get the client to call the delegate directly.

Mechanism Create an accessor for the delegate. For each client use of a delegate method, remove the method from the server and replace the call in the client to call method on the delegate. Compile and test after each change.

Introduce Foreign Method A server class you are using needs an additional method, but you can't modify the class. Create a method in the client class with an instance of the server class as its first argument.

Mechanism Create a method in the client class that does what you need. The method should not access any of the features of the client class. If it needs a value, send it in as a parameter. Make an instance of the server class the first parameter. Compile and test. Comment the method as "foreign method; should be in server." This way you can use a text search to find foreign methods later if you get the chance to move the method.

Example Date newStart = new Date (previousEnd.getYear(), previousEnd.getMonth(), previousEnd.getDate() + 1); Date newStart = nextDay(previousEnd); private static Date nextDay(Date arg) { // foreign method, should be on Date return new Date (arg.getYear(),arg.getMonth(), arg.getDate() + 1); }

Introduce Local Extension A server class you are using needs several additional methods, but you can't modify the class. Create a new class that contains these extra methods. Make this extension class a subclass or a wrapper of the original.

Mechanics Create an extension class either as a subclass or a wrapper of the original. Add converting constructors to the extension. A constructor takes the original as an argument. The subclass version calls an appropriate superclass constructor; the wrapper version sets the delegate field to the argument. Add new features to the extension. Replace the original with the extension where needed. Move any foreign methods defined for this class onto the extension.

Extend Date: Subclass Method class MfDateSub extends Date public MfDateSub (String dateString) { super (dateString); } public MfDateSub (Date arg) { super (arg.getTime()); public nextDay()... public dayOfYear()...

Extend Date: Wapper Method class mfDateWrap { private Date _original; public MfDateWrap (String dateString) { _original = new Date(dateString); } public MfDateWrap (Date arg) { _original = arg; public int getYear() { return _original.getYear(); public boolean equals (MfDateWrap arg) { return (toDate().equals(arg.toDate()));