Today’s Agenda  More refactoring patterns Software Testing and Maintenance 1.

Slides:



Advertisements
Similar presentations
Inheritance // A simple class hierarchy. // A class for two-dimensional objects. class TwoDShape { double width; double height; void showDim() { System.out.println("Width.
Advertisements

About Me – Frank Xu Education ▫ North Dakota State University  Ph.D. in Software Engineering ▫ Towson University  MS in Computer Science ▫ Southeast.
Written by: Dr. JJ Shepherd
Software Testing and Maintenance 1 Today’s Agenda  Course Evaluation  HW 4 Return  HW 5 Correction  Quiz 4 Next Class  Software Refactoring.
Refactoring: Improving the Design of Existing Code © Martin Fowler, Martin Fowler.
1 Introduction to CS Agenda Syllabus Schedule Lecture: the management of complexity.
REFACTORING Improving the Design of Existing Code Atakan Şimşek e
Refactoring, continue. Announcements Due today Resubmit HW5 (feedback on HW5 in SVN) HW7 HW8 will be up tonight Due Saturday at 5:59! Quiz 9 Spring 15.
Previous Exam 1.0. Question 1 - a Is the following statement true or false? Briefly explain your answer. A && B is the same as B && A for any Boolean.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
Java File Structure.  File class which is defined by java.io does not operate on streams  deals directly with files and the file system  File class.
Intro to OOP with Java, C. Thomas Wu
1 v1.6 08/02/2006 Overview of Eclipse Lectures 1.Overview 2.Installing and Running 3.Building and Running Java Classes 4.Refactoring 5.Debugging 6.Testing.
Refactoring: Improving the Design of Existing Code © Martin Fowler, Martin Fowler.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
Chapter 6: Code Refactoring Omar Meqdadi SE 3860 Lecture 6 Department of Computer Science and Software Engineering University of Wisconsin-Platteville.
Refactoring - A disciplined approach to rework for better design.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
Chap. 1 Classes, Types, and Objects. How Classes Are Declared [ ] class [extends ] [implements,, … ] { // class methods and instance variable definitions.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
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.
Mohammed Al-Dhelaan CSci 253 Object Oriented Design Instructor: Brad Taylor 06/02/2009 Factory Method Pattern.
Java The Java programming language was created by Sun Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since A programming.
Refactoring: Improving the Design of Existing Code © Martin Fowler, Martin Fowler.
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 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.
Software Construction and Evolution - CSSE 375 Making Method Calls Simpler Shawn and Steve Below – “Be the character!” The late acting teacher Lee Strasberg.
1 Software Maintenance and Evolution CSSE 575: Session 3, Part 3 Dealing with Generalization Steve Chenoweth Office Phone: (812) Cell: (937)
Refactoring. Announcements HW7 due today, HW8 coming up tomorrow (I’m taking a late day on posting HW8) Grades and feedback for HW0-5 in Homework Server.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CSSE 375 Organizing Data – Part 2 Shawn and Steve Continue the same quiz!
Refactoring1 Improving the structure of existing code.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Written by: Dr. JJ Shepherd
Software Construction and Evolution - CSSE 375 Simplifying Conditionals Shawn & Steve.
Refactoring Constants and Variables Lesson Three: Constants and Variables.
CSSE 375 Organizing Data – Part 1 Shawn and Steve Q1.
REFACTORING CHANGE VALUE TO REFERENCE SUBSTITUTE ALGORITHM REPLACE CONDITIONAL WITH POLYMORHPISM.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
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.
Refactoring Improving code after it has been written.
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.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
Catalog of Refactoring (3) Organizing Data. Catalog Self Encapsulate Field Replace Data Value with Object Change Value to Reference Change Reference to.
Catalog of Refactoring (5) Simplifying Conditional Expressions.
Week 5 Extending classes in Java. Extending classes u Using an existing classes as the basis for a new one u Defining only the differences between the.
Catalog of Refactoring (6) Making Method Calls Simpler.
Refactoring (1). Software Evolution Cope with change Feature bloat Design decay Code duplications “Pattern time is refactoring time” Make future changes.
A (Very) Simple Example Consolidate duplicate conditional fragments if (isSpecialDeal()) { total = price * 0.95; send (); } else { total = price * 0.98;
Catalog of Refactoring
Module Road Map Refactoring Why Refactoring? Examples
Inheritance and Polymorphism
Outline A. What is Refactoring? B. Why do we Refactor?
Lecture 15: More Inheritance
Refactoring Methods: Kevin Murphy.
University of Central Florida COP 3330 Object Oriented Programming
Extract Subclass, Extract Superclass and Extract Hierarchy
Refactorings Luke Marsh.
null, true, and false are also reserved.
Overview of Eclipse Lectures
Java Programming Language
Improving the structure of existing code
Lecture 15: Inheritance II
Presentation transcript:

Today’s Agenda  More refactoring patterns Software Testing and Maintenance 1

Introduce Null Object (1) class Site … Customer getCustomer () { return _customer; } class Customer … public String getName () { … } public BillingPlan getPlan () { … } public PaymentHistory getHistory () { … } Customer customer = site.getCustomer (); BillingPlan plan; if (customer == null) plan = BillingPlan.basic (); else plan = customer.getPlan (); … String customerName; if (customer == null) customerName = “occupant”; else customerName = customer.getName (); … Software Testing and Maintenance 2

Introduce Null Object (2) class NullCustomer extends Customer { public boolean isNull () { return true; } public String getName () { return “occupant”; } public BillingPlan getPlan () { return BillingPlan.basic (); } class Customer … static Customer newNull () { return new NullCustomer (); } class Site … Customer getCustomer () { return (_customer == null) ? Customer.newNull () : _customer; } Software Testing and Maintenance 3

Introduce Null Object (3) Customer customer = site.getCustomer (); BillingPlan plan; plan = customer.getPlan (); … String customerName; customerName = customer.getName (); … Software Testing and Maintenance 4

Replace Data Value with Object (1) class Order public Order (String customer) { _customer = customer; } public String getCustomer () { return _customer; } public void setCustomer (String customer) { _customer = customer; } private String _customer; Software Testing and Maintenance 5 What if we need to add address or credit rating into a customer?

Replace Data Value with Object (2) class Customer { public Customer (String name) { _name = name; } public String getName () { return _name; } private final String _name; } class Order … public order (String customer) { _customer = new Customer (customer); } public String getCustomer () { return _customer.getName (); } private Customer _customer; public void setCustomer (String customer) { _customer = new Customer (customer); } Software Testing and Maintenance 6

Change Value to Reference class Order { public order (String customer) { _customer = Customer.create (customer); } class Customer { private Customer (String name) { _name = name; } static void loadCustomer () { new Customer (“Bilston Gasworks”).store(); new Customer (“Jeff Bridge”).store(); … } private void store () { _instances.put(this.getName(), this); } public static Customer create (String name) { return (Customer) _instances.get(name); } private static Dictionary _instances = new Hashtable (); } Software Testing and Maintenance 7

Replace Magic Number with Sym. Constant double potentialEnergy (double mass, double height) { return mass * 9.81 * height; } Software Testing and Maintenance 8 double potentialEnergy (double mass, double height) { return mass * GRAVITATIONAL_CONSTANT * height; } Static final double GRAVITATIONAL_CONSTANT = 9.81;

Separate Query from Modifier int getTotalOutstandingAndSetReadyForSummaries () { readyForSummaries = true; return outstanding; } Software Testing and Maintenance 9 int getTotalOutstanding () { return outstanding; } void setReadyForSummaries () { readyForSummaries = true; }

Parameterize Method class Employee { void tenPercentRaise () { salary *= 1.1; } void fivePercentRaise () { salary *= 1.05; } Software Testing and Maintenance 10 class Employee { void raise (double factor) { salary *= (1 + factor); }

Replace Parameter with Explicit Methods void setValue (String name, int value) { if (name.equals(“height”)) { _height = value; return; } if (name.equals(“width”)) { _width = value; return; } Software Testing and Maintenance 11 void setHeight (int arg) { _height = arg; } Void setWidth (int arg) { _width = arg; }

Replace Parameter with Method (1) public double getPrice () { int basePrice = _quantity * _itemPrice; int discountLevel; if (_quantity > 100) discountLevel = 2; else discountLevel = 1; double finalPrice = discountedPrice (basePrice, discountLevel); return finalPrice; } private double discountedPrice (int basePrice, int discountLevel) { if (discountLevel == 2) return basePrice * 0.1; else return basePrice * 0.05; } Software Testing and Maintenance 12

Replace Parameter with Method (2) public double getPrice () { if (getDiscountLevel() == 2) return getBasePrice() * 0.1; else return getBasePrice() * 0.05; } private double getBasePrice () { return _quantity * _itemPrice; } private int getDiscountLevel () { if(_quantity > 100) return 2; else return 1; } Software Testing and Maintenance 13

Replace Constructor with Factory Method (1) class Employee { private int _type; static final int ENGINEER = 0; static final int SALESMAN = 1; static final int MANAGER = 2; Employee (int type) { _type = type; } Software Testing and Maintenance 14 class Employee { static Employee create (int type) { switch (type) { case ENGINEER: return new Engineer (); case SALESMAN: return new Salesman (); case MANAGER: return new Manager (); default: // throw an exception }

Replace Constructor with Factory Method (2) Software Testing and Maintenance 15 static Employee create (String name) { try { return (Employee) Class.forName (name).newInstance(); } catch (Exception ex) { throw new IllegalArgumentException(“Unable to instantiate ” + name); } Employee.create(“Engineer”); Employee.create(“Manager”); …

Encapsulate Downcast Object lastReading () { return readings.lastElement (); } Reding lastReading = (Reading) site.lastReading (); Software Testing and Maintenance 16 Reading lastReading () { return (Reading) readings.lastElement (); } Reding lastReading = site.lastElement();

Replace Error Code with Exception (1) class Account … int withdraw (int amount) { if (amount > _balance) return -1; else { _balance -= amount; return 0; } private int _balance; Software Testing and Maintenance 17

Replace Error Code with Exception (2) class Account … void withdraw (int amount) { if (amount > _balance) throw new IllegalArgumentException (“Amount too large”); _balance -= amount; } private int _balance; Software Testing and Maintenance 18

Replace Error Code with Exception (3) class Account … void withdraw (int amount) throws BalanceException { if (amount > _balance) throw new BalanceException (); _balance -= amount; } private int _balance; Software Testing and Maintenance 19

Pull Up Constructor Body class Manager extends Employee … public Manager (String name, String id, int grade) { _name = name; _id = id; _grade = grade; } Software Testing and Maintenance 20 class Employee … public Employee (String name, string id) { _name = name; _id = id; } class Manager extends Employee … public Manager (String name, String id, int grade) { super (name, id); _grade = grade; }

Extract Subclass (1) class JobItem … public JobItem (int unitPrice, int quantity, boolean isLabor, Employee employee) { _unitPrice = unitPrice; _quantity = quantity; … } public int getTotalPrice () { return getUnitPrice () * quantity; } public int getUnitPrice () { return (_isLabor) ? _employee.getRate() : _unitPrice; } …. class Employee… public Employee (int rate) { _rate = rate; } public int getRate () { return _rate; } private _rate; Software Testing and Maintenance 21

Extract Subclass (2) class JobItem … public JobItem (int unitPrice, int quantity, boolean isLabor) { _unitPrice = unitPrice; _quantity = quantity; _isLabor = isLabor; } public int getUnitPrice () { return _unitPrice; } …. class LaborItem extends JobItem … public LaborItem (int quantity, Employee employee) { super (0, quantity, true); _employee = employee; } public int getUnitPrice () { return _employee.getRate (); } Software Testing and Maintenance 22

Extract Subclass (3)  Modify calls to the constructor of the job item where a labor item is constructed Software Testing and Maintenance 23 JobItem j = new JobItem (0, 5, true, kent); JobItem j = new LaborItem (5, kent);

Form Template Method (1) public String statement () { Enumeration rentals = _rentals.elements (); String result = “Rental Record for ” + getName () + “\n”; while (rentals.hasMoreElements ()) { Rental each = (Rental) rentals.nextElement (); // show figures for this rental result += “\t” + each.getMovie.getTitle() + “\t” + String.valueOf(each.getCharge()) + “\n”; } // add footer lines result += “Amount owed is“ + String.valueOf(getTotalCharge()) + “\n”; result += “You earned “ + String.valueOf(getTotalFrequentRenterPoints()) + “ frequent renter points”; return result; } Software Testing and Maintenance 24

Software Testing and Maintenance 25 Form Template Method (2) public String htmlStatement () { Enumeration rentals = _rentals.elements (); String result = “ Rental Record for ” + getName () + “ \n”; while (rentals.hasMoreElements ()) { Rental each = (Rental) rentals.nextElement (); // show figures for this rental result += each.getMovie.getTitle() + “: ” + String.valueOf(each.getCharge()) + “ \n”; } // add footer lines result += “ You owe “ + String.valueOf(getTotalCharge()) + “ \n”; result += “On this rental you earned “ + String.valueOf(getTotalFrequentRenterPoints()) + “ frequent renter points ”; return result; }

Form Template Method (3) Software Testing and Maintenance 26 CustomerStatement Text Statement HTML Statement

Software Testing and Maintenance 27 Form Template Method (4) class Statement … public String value (Customer customer) { Enumeration rentals = customer.getRentals (); String result = headerString(customer); while (rentals.hasMoreElements ()) { Rental each = (Rental) rentals.nextElement (); // show figures for this rental result += eachRentalString(each); } // add footer lines result += footerString(customer); return result; } abstract String headerString (Customer customer); abstract String eachRentalString (Rental rental); abstract String footerString (Customer customer);

Software Testing and Maintenance 28 Form Template Method (5) class TextStatement … String headerString (Customer customer) { return “Rental Record for “ + customer.getName () + “\n”; } String eachRentalString (Rental rental) { return “\t” + rental.getMovie().getTitle() + “\t” + String.valueOf(rental.getCharge() + “\n”; } String footerString (Customer customer) { return “Amount owed is “ + String.valueOf(customer.getTotalCharge()) + “\n” + “You earned “ + String.valueOf(customer.getTotalFrequentRenterPoints()) + “ frequent renter points”; } // similar for class HtmlStatement

Replace Inheritance with Delegation (1) class MyStack extends Vector { public void push (Object element) { insertElementAt (element, 0); } public Object pop () { Object result = firstElement (); removeElementAt (0); return result; } Software Testing and Maintenance 29

Replace Inheritance with Delegation (2) class MyStack { private Vector _vector = new Vector (); public void push (Object element) { _vector.insertElementAt (element, 0); } public Object pop () { Object result = _vector.firstElement (); _vector.removeElementAt (0); return result; } public int size () { return _vector.size (); } public boolean isEmpty () { return _vector.isEmpty (); } Software Testing and Maintenance 30