REFACTORING CHANGE VALUE TO REFERENCE SUBSTITUTE ALGORITHM REPLACE CONDITIONAL WITH POLYMORHPISM.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

Chapter 11 Component-Level Design
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Reusable Classes.  Motivation: Write less code!
A practical guide John E. Boal TestDrivenDeveloper.com.
Written by: Dr. JJ Shepherd
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
Software Engineering Key Refactorings
Introduction to Data Structures, Spring 2007 Slide- 1 California State University, Fresno Introduction to Data Structure Object Oriented Programming Concepts.
Object Concepts in C# Class, object, attribute, method, message, instance, encapsulation, polymorphism, inheritance, association, persistence, Generalization/specialization,
Template Method By: Mahmoodreza Jahanseir Amirkabir University of Technology Computer Engineering Department Fall 2010.
Chapter 10 Classes Continued
Maintenance Refactoring and Code Smells. Where are we? Over the semester we have talked about Software Engineering. The overall goal of software engineering.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Chapter 15 – Inheritance, Virtual Functions, and Polymorphism
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Design patterns. What is a design pattern? Christopher Alexander: «The pattern describes a problem which again and again occurs in the work, as well as.
Introduction to Java Prepared by: Ahmed Hefny. Outline Classes Access Levels Member Initialization Inheritance and Polymorphism Interfaces Inner Classes.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Abstract Factory Pattern. What Is an Abstract Factory Pattern?  The Abstract Factory pattern is a creative way to expand on the basic Factory pattern.
SWE 316: Software Design and Architecture Objectives Lecture # 20 Improving the existing design: Refactoring SWE 316: Software Design and Architecture.
1 Computer Science 340 Software Design & Testing Inheritance.
Refactoring Deciding what to make a superclass or interface is difficult. Some of these refactorings are helpful. Some research items include Inheritance.
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
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.
Today’s Agenda  More refactoring patterns Software Testing and Maintenance 1.
Creational Pattern: Factory Method At times, a framework is needed to standardize the behavior of objects that are used in a range of applications, while.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
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.
Refactoring Conditionals Lesson Five: Conditionals.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
Object Oriented Programming
Software Construction and Evolution - CSSE 375 Making Method Calls Simpler Shawn and Steve Below – “Be the character!” The late acting teacher Lee Strasberg.
ISBN Object-Oriented Programming Chapter Chapter
CSSE 375 Organizing Data – Part 2 Shawn and Steve Continue the same quiz!
Proxy Pattern defined The Proxy Pattern provides a surrogate or placeholder for another object to control access to it by creating a representative object.
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 Simplifying Conditionals Shawn & Steve.
CSSE 375 Organizing Data – Part 1 Shawn and Steve Q1.
Presented by Ted Higgins, SQL Server DBA An Introduction to Object – Oriented Programming.
Inheritance ndex.html ndex.htmland “Java.
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 (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.
JAVA ACCESS MODIFIERS. Access Modifiers Access modifiers control which classes may use a feature. A classes features are: - The class itself - Its member.
Catalog of Refactoring (6) Making Method Calls Simpler.
Catalog of Refactoring
Module Road Map Refactoring Why Refactoring? Examples
Advanced Java Topics Chapter 9
Week 2, Day 1: The Factory Method Pattern
Inheritance and Polymorphism
Refactoring Methods: Kevin Murphy.
Refactoring and Code Smells
SWEN-610 Foundations of Software Engineering
Component-Level Design
Overview of Eclipse Lectures
Advanced Java Topics Chapter 9
Week 6 Object-Oriented Programming (2): Polymorphism
Advanced Programming Behnam Hatami Fall 2017.
Refactoring and Code Smells
Singleton Pattern Pattern Name: Singleton Pattern Context
Refactoring and Code Smells
CIS 199 Final Review.
Designing For Testability
Chapter 5 Classes.
Refactoring and Code Smells
Presentation transcript:

REFACTORING CHANGE VALUE TO REFERENCE SUBSTITUTE ALGORITHM REPLACE CONDITIONAL WITH POLYMORHPISM

SUBSTITUTE ALGORITHM - MOTIVATION What’s Wrong? Hard to read Tedious to Modify Lengthy String foundPerson(String[] people){ for (int i = 0; i < people.length; i++) { if (people[i].equals ("Don")){ return "Don"; } if (people[i].equals ("John")){ return "John"; } if (people[i].equals ("Kent")){ return "Kent"; } } return ""; }

SUBSTITUTE ALGORITHM - EXAMPLE String foundPerson(String[] people){ List candidates = Arrays.asList(new String[] {"Don", "John", "Kent"}); for (int i=0; i<people.length; i++) if (candidates.contains(people[i])) return people[i]; return ""; } String foundPerson(String[] people){ for (int i = 0; i < people.length; i++) { if (people[i].equals ("Don")){ return "Don"; } if (people[i].equals ("John")){ return "John"; } if (people[i].equals ("Kent")){ return "Kent"; } } return ""; } Benefits: Shorter Easier to Read Add people by changing list No need to change control

CHANGE VALUE TO REFERENCE - MOTIVATION class Customer { public Customer (String name) { _name = name; } public String getName() { return _name; } private final String _name; } class Order... public Order (String customerName) { _customer = new Customer(customerName); } public void setCustomer(String customerName) { _customer = new Customer(customerName); } public String getCustomerName() { return _customer.getName(); } private Customer _customer; private static int numberOfOrdersFor(Collection orders, String customer) { int result = 0; Iterator iter = orders.iterator(); while (iter.hasNext()) { Order each = (Order) iter.next(); if (each.getCustomerName().equals(customer)) result++; } return result; } Classes Problems Each new order creates a new customer object Each customer can have many orders A lot of wasteful storage Client Code Example

CHANGE VALUE TO REFERENCE - EXAMPLE Load customers from DB in advance private static Dictionary _instances = new Hashtable(); class Customer... private Customer (String name) { _name = name; } static void loadCustomers() { new Customer ("Lemon Car Hire").store(); new Customer ("Associated Coffee Machines").store(); new Customer ("Bilston Gasworks").store(); } private void store() { _instances.put(this.getName(), this); } public static Customer getNamed (String name) { return (Customer) _instances.get(name); } Use a hash table to store/retrieve customers Private constructor to disallow new customer creation Factory method to handle customer creation SHOULD be from DB explicit code for example Store existing customers in hashtable Return the instance (reference) of customer with “name”

CHANGE VALUE TO REFERENCE - BENEFIT Customer class can reference existing customers Many orders can reference the same customer If a customer has a data change, the orders will not have to get new data or create new data. The referenced object changes for the orders class Order { public Order (String customer) { _customer = Customer.getNamed(customer); }

REPLACE CONDITIONAL WITH POLYMORPHISM - MOTIVATION Avoid writing an explicit conditional when you have objects whose behavior varies depending on their types. If you want to add a new Employee Type subclass you have to find and update all the conditionals Avoid high coupling between Employee Type and sub classes

class EmployeeType... int payAmount(Employee emp) { switch (getTypeCode()) { case ENGINEER: return emp.getMonthlySalary(); case SALESMAN: return emp.getMonthlySalary() + emp.getCommission(); case MANAGER: return emp.getMonthlySalary() + emp.getBonus(); default: throw new RuntimeException("Incorrect Employee"); } } REPLACE CONDITIONAL WITH POLYMORPHISM - EXAMPLE Different calculation for each paycheck High Coupling Let subclasses override payAmount class EmployeeType... abstract int payAmount(Employee emp); We Want:

REPLACE CONDITIONAL WITH POLYMORPHISM - EXAMPLE class EmployeeType... abstract int payAmount(Employee emp); We Want: class Employee... int payAmount() { return _type.payAmount(this); } class Engineer... int payAmount(Employee emp) { return emp.getMonthlySalary(); } class EmployeeType... int payAmount(Employee emp) { switch (getTypeCode()) { case ENGINEER: throw new RuntimeException ("Should be being overridden"); case SALESMAN: return emp.getMonthlySalary() + emp.getCommission(); case MANAGER: return emp.getMonthlySalary() + emp.getBonus(); default: throw new RuntimeException("Incorrect Employee"); } } ADDMODIFY

REPLACE CONDITIONAL WITH POLYMORPHISM - EXAMPLE class EmployeeType... abstract int payAmount(Employee emp); We Want: class Manager... int payAmount(Employee emp) { return emp.getMonthlySalary() + emp.getBonus(); } class EmployeeType... int payAmount(Employee emp) { switch (getTypeCode()) { case ENGINEER: throw new RuntimeException ("Should be being overridden"); case SALESMAN: throw new RuntimeException ("Should be being overridden"); case MANAGER: throw new RuntimeException ("Should be being overridden"); default: throw new RuntimeException("Incorrect Employee"); } } ADDMODIFY class Salesman... int payAmount(Employee emp) { return emp.getMonthlySalary() + emp.getCommission(); }

REPLACE CONDITIONAL WITH POLYMORPHISM - BENEFIT class EmployeeType... int payAmount(Employee emp) { switch (getTypeCode()) { case ENGINEER: throw new RuntimeException ("Should be being overridden"); case SALESMAN: throw new RuntimeException ("Should be being overridden"); case MANAGER: throw new RuntimeException ("Should be being overridden"); default: throw new RuntimeException("Incorrect Employee"); } } class EmployeeType... abstract int payAmount(Employee emp); No need to modify control structure Higher cohesion, lower coupling Reduces dependencies Easier to update / add new employee types BENEFIT

QUESTIONS?