Lecture 12, part 2: Refactoring. NCCU Fall 2005 Dec. 13, 2005

Size: px
Start display at page:

Download "Lecture 12, part 2: Refactoring. NCCU Fall 2005 Dec. 13, 2005"

Transcription

1 Lecture 12, part 2: Refactoring NCCU Fall 2005 Dec. 13,

2 Refactoring 什? 不 行 理 降 行 不 Unit Testing! Martin Fowler (and Kent Beck, John Brant, William Opdyke, Don Roberts), Refactoring- Improving the Design of Existing Code, Addison Wesley,

3 不 行 類 3

4 Refactoring Refactoring (noun): a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior. Refactor (verb): to restructure software by applying a series of refactorings. 4

5 行? Bug Code Review bad smell 5

6 Bad smells 不 說 (bad smell) 易 Bad Smell Peer Review Bad Smell Bad Smell 6

7 Bad Smell Examples Duplicate Code Long Methods Large Classes Long Parameter Lists Too Many Case Statements 數 不良 Code Standard 7

8 Visible refactoring UML 8

9 Invisible refactoring Collection if 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 ""; 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 ""; UML 不 9

10 :Make changes as small as possible. Many small changes are easier than one big change. :Test after each change. 10

11 Test-Driven Start Choose task Y Done? N Write a new, small test Refactor run tests Implement just enough so that the test will fail y n code smells? y green? n implement just enough so that tests should pass 11

12 Refactoring Book Book has a catalogue of: 22 bad smells i.e., things to look out for, anti-patterns 72 refactorings i.e., what to do when you find them. As with GoF book on OODPs, there is overlap between the catalogue items, and the ideas start to blur. 12

13 Typical Refactorings Class Refactorings Method Refactorings Attribute Refactorings add (sub)class to hierarchy add method to class add variable to class rename class rename method rename variable remove class remove method remove variable push method down push method up add parameter to method move method to component push variable down push variable up create accessors abstract variable extract code in new method These simple refactorings can be combined to provide bigger restructurings such as the introduction of design patterns. 13

14 Some Frequently Used Refactorings Extract method Pull-up method Move method Move field Replace temp with query Replace conditional logic with polymorphism Replace type code with Strategy/State pattern Extract class 14

15 Extract method example //identify the problem methoda() { //code <Subroutine> Extract the subroutine: <Subroutine> Put it into a method: methodb() { //code <Subroutine> (similar to subroutine in methoda) //Replace extracted code methoda() { //code methodc(); methodc() { <Subroutine> methodb() { //code methodc(); 15

16 Farm template method Same code in two related classes. Farm template method: Push commonalities into closest mutual ancestor. Ancestor Class A Class B 16

17 Pull Up Method 17

18 Replace Type Code with State/Strategy 18

19 Refactoring, applied Straight from the book: a program to calculate and print a statement of a customer s charges at a video store...price depends on how long the movie is rented and the category of the movie...also compute frequent renter points 19

20 Refactoring: Movie Class diagram of the starting point classes. Movie PriceCode: int Rental 1 * * daysrented: int 1 Customer Statement() 20

21 Refactoring: Movie Class public class Movie { public static final int CHILDREN=2; public static final int REGULARS=0; public static final int NEW_RELEASE=1; private String _title; private int _pricecode; public void setpricecode(int arg) { _pricecode = arg; public String gettitle() { return _title; public Movie(String title, int pricecode) { _title=title; _pricecode = pricecode; public int getpricecode() { return _pricecode; 21

22 Refactoring: Rental Class public class Rental { private Movie _movie; private int _daysrented; public Rental(Movie movie, int daysrented) { _movie = movie; _daysrented = daysrented ; public int getdaysrented() { return _daysrented ; public Movie getmovie() { return _movie; 22

23 Refactoring: Customer Class public class Customer { private String _name; private Vector _rentals =new Vector(); public Customer(String name) { _name = name; public void addrental(rental arg) { _rentals.addelement(arg); public String getname() { return _name; 23

24 Refactoring: Customer Class public class Customer... public String statement() { double totalamount = 0; int frequentrenterpoints = 0; Enumeration rentals = _rental.elements(); String result = Rental Record for + getname() + \n ; while (rentals.hasmoreelements()) { double thisamount = 0; Rental each = (Rental) rentals.nextelement(); // determine amounts for each line switch (each.getmovie().getpricecode()) { case Movie.REGULAR: thisamount += 2; if (each.getdaysrented() > 2) thisamount+=(each.getdaysrented()-2) * 1.5; break; 24

25 Refactoring: Customer Class public class Customer public String statement()... case Movie.NEW_RELEASE: thisamount += each.getdaysrented() * 3; break; case Movie.CHILDRENS: thisamount += 1.5; if (each.getdaysrented() > 3) thisamount+=(each.getdaysrented()-3) * 1.5; break; // add frequent renter points frequentrenterpoints ++; // add bonus for a two day new release rental if ((each.getmovie().getpricecode() == Movie.NEW_RELEASE)&& each.getdaysrented() > 1) frequentrenterpoints++; 25

26 Refactoring: Customer Class public class Customer public String statement()... //show figures for this rental result += \t + each.getmovie().gettitle()+ \t + String.valueOf(thisAmount) + \n ; totalamount += thisamount; // add footer lines result += Amount owed is +Sting.valueOf(totalAmount) + \n ; result += You earned +Sting.valueOf(frequentRenterPoints) + frequent renter points\n ; return result; 26

27 Refactoring Sequence diagram for the statement method. 27

28 Refactoring: problem statement Add a htmlstatment method which returns a customer statement string containing html tags....and there will be some changes to the way movies are classified...affecting frequent renter points and charging. 28

29 Refactoring: step 1 Write a test suite! Refactoring should not affect the outcome of tests. The test suite must exercise the published interface of the classes. Obviously, refactoring should not affect the published interface. So, avoid publishing interfaces too early. 29

30 Refactoring: step 2 statement() is overly long, apply the Extract Method refactoring public String statement() { double totalamount = 0; int frequentrenterpoints = 0; Enumeration rentals = _rental.elements(); String result = Rental Record for + getname() + \n ; while (rentals.hasmoreelements()) { double thisamount = 0; Rental each = (Rental) rentals.nextelement(); // determine amounts for each line switch (each.getmovie().getpricecode()) { case Movie.REGULAR: thisamount += 2; if (each.getdaysrented() > 2) thisamount+=(each.getdaysrented()-2) * 1.5; break; case Movie.NEW_RELEASE: thisamount += each.getdaysrented() * 3; break; case Movie.CHILDRENS: thisamount += 1.5; if (each.getdaysrented() > 3) thisamount+=(each.getdaysrented()-3) * 1.5; break; 30

31 Refactoring: step 2 public String statement() { double totalamount = 0; int frequentrenterpoints = 0; Enumeration rentals = _rental.elements(); String result = Rental Record for + getname() + \n ; while (rentals.hasmoreelements()) { double thisamount = 0; Rental each = (Rental) rentals.nextelement(); thisamount = amountfor(each); // add frequent renter points frequentrenterpoints ++; // add bonus for a two day new release rental if ((each.getmovie().getpricecode() == Movie.NEW_RELEASE)&& each.getdaysrented() > 1) frequentrenterpoints++; //show figures for this rental result += \t + each.getmovie().gettitle()+ \t + String.valueOf(thisAmount) + \n ; totalamount += thisamount; // add footer lines result += Amount owed is +Sting.valueOf(totalAmount) + \n ; result += You earned +Sting.valueOf(frequentRenterPoints) + frequent renter points\n ; return result; 31

32 Refactoring: step 2 public int amountfor(rental each) { int thisamount = 0; switch (each.getmovie().getpricecode()) { case Movie.REGULAR: thisamount += 2; if (each.getdaysrented() > 2) thisamount+=(each.getdaysrented()-2) * 1.5; break; case Movie.NEW_RELEASE: thisamount += each.getdaysrented() * 3; break; case Movie.CHILDRENS: thisamount += 1.5; if (each.getdaysrented() > 3) thisamount+=(each.getdaysrented()-3) * 1.5; break; return thisamount; 32

33 Refactoring: step 3 TEST 33

34 Refactoring: step 4 oops, (double) -> (int) bug! public double amountfor(rental each) { double thisamount = 0; switch (each.getmovie().getpricecode()) { case Movie.REGULAR: thisamount += 2; if (each.getdaysrented() > 2) thisamount+=(each.getdaysrented()-2) * 1.5; break; case Movie.NEW_RELEASE: thisamount += each.getdaysrented() * 3; break; case Movie.CHILDRENS: thisamount += 1.5; if (each.getdaysrented() > 3) thisamount+=(each.getdaysrented()-3) * 1.5; break; return thisamount; 34

35 Refactoring: step 5 Variable names not helpful public double amountfor(rental each) { double thisamount = 0; switch (each.getmovie().getpricecode()) { case Movie.REGULAR: thisamount += 2; if (each.getdaysrented() > 2) thisamount+=(each.getdaysrented()-2) * 1.5; break; case Movie.NEW_RELEASE: thisamount += each.getdaysrented() * 3; break; case Movie.CHILDRENS: return thisamount; thisamount += 1.5; if (each.getdaysrented() > 3) thisamount+=(each.getdaysrented()-3) * 1.5; break; 35

36 Refactoring: step 5 public double amountfor(rental arental) { double result = 0; switch (arental.getmovie().getpricecode()) { case Movie.REGULAR: result += 2; if (arental.getdaysrented() > 2) result +=(arental.getdaysrented()-2) * 1.5; break; case Movie.NEW_RELEASE: result += arental.getdaysrented() * 3; break; case Movie.CHILDRENS: result += 1.5; if (arental.getdaysrented() > 3) result +=(arental.getdaysrented()-3) * 1.5; break; return result ; 36

37 Refactoring: step 6 Moving amount computation (does not use info from Customer, only Rental) class Customer... public double amountfor(rental arental) { double result = 0; switch (arental.getmovie().getpricecode()) { case Movie.REGULAR: result += 2; if (arental.getdaysrented() > 2) result +=(arental.getdaysrented()-2) * 1.5; break; case Movie.NEW_RELEASE: result += arental.getdaysrented() * 3; break; case Movie.CHILDRENS: result += 1.5; if (arental.getdaysrented() > 3) result +=(arental.getdaysrented()-3) * 1.5; break; return result ; 37

38 Refactoring: step 6 class Rental... public double getcharge() { double result = 0; switch (getmovie().getpricecode()) { case Movie.REGULAR: result += 2; if (getdaysrented() > 2) result +=(getdaysrented()-2) * 1.5; break; case Movie.NEW_RELEASE: result += getdaysrented() * 3; break; case Movie.CHILDRENS: return result ; result += 1.5; if (getdaysrented() > 3) result +=(getdaysrented()-3) * 1.5; break; 38

39 Refactoring: step 6 class Customer... public double amountfor(rental arental) { return arental.getcharge(); 39

40 Refactoring: step 7 class Customer... public String statement() { double totalamount = 0; int frequentrenterpoints = 0; Enumeration rentals = _rental.elements(); String result = Rental Record for + getname() + \n ; while (rentals.hasmoreelements()) { double thisamount = 0; Rental each = (Rental) rentals.nextelement(); thisamount = amountfor(each); // add frequent renter points frequentrenterpoints ++; // add bonus for a two day new release rental if ((each.getmovie().getpricecode() == Movie.NEW_RELEASE)&& each.getdaysrented() > 1) frequentrenterpoints++; //show figures for this rental result += \t + each.getmovie().gettitle()+ \t + String.valueOf(thisAmount) + \n ; totalamount += thisamount; // add footer lines result += Amount owed is +Sting.valueOf(totalAmount) + \n ; result += You earned +Sting.valueOf(frequentRenterPoints) + frequent renter points\n ; return result; 40

41 Refactoring: step 7 class Customer... public String statement() { double totalamount = 0; int frequentrenterpoints = 0; Enumeration rentals = _rental.elements(); String result = Rental Record for + getname() + \n ; while (rentals.hasmoreelements()) { double thisamount = 0; Rental each = (Rental) rentals.nextelement(); thisamount = each.getcharge(); // add frequent renter points frequentrenterpoints ++; // add bonus for a two day new release rental if ((each.getmovie().getpricecode() == Movie.NEW_RELEASE)&& each.getdaysrented() > 1) frequentrenterpoints++; //show figures for this rental result += \t + each.getmovie().gettitle()+ \t + String.valueOf(thisAmount) + \n ; totalamount += thisamount; // add footer lines result += Amount owed is +Sting.valueOf(totalAmount) + \n ; result += You earned +Sting.valueOf(frequentRenterPoints) + frequent renter points\n ; return result; 41

42 Refactoring State of classes after moving the charge method. amountfor has been deleted. Movie Rental 1 * Customer PriceCode: int * daysrented: int 1 getcharge() Statement() 42

43 Refactoring: step 8 Replace Temp with Query (thisamount is redundant) class Customer... class Customer... public String statement() { double totalamount = 0; int frequentrenterpoints = 0; Enumeration rentals = _rental.elements(); String result = Rental Record for + getname() + \n ; while (rentals.hasmoreelements()) { Rental each = (Rental) rentals.nextelement(); // add frequent renter points frequentrenterpoints ++; // add bonus for a two day new release rental if ((each.getmovie().getpricecode() == Movie.NEW_RELEASE)&& each.getdaysrented() > 1) frequentrenterpoints++; //show figures for this rental result += \t + each.getmovie().gettitle()+ \t + String.valueOf(each.getCharge()) + \n ; totalamount += each.getcharge(); // add footer lines result += Amount owed is +Sting.valueOf(totalAmount) + \n ; result += You earned +Sting.valueOf(frequentRenterPoints) + frequent renter points\n ; return result; 43

44 Refactoring: step 9 Extract Method (frequent renter computation) class Customer... public String statement() { double totalamount = 0; int frequentrenterpoints = 0; Enumeration rentals = _rental.elements(); String result = Rental Record for + getname() + \n ; while (rentals.hasmoreelements()) { Rental each = (Rental) rentals.nextelement(); // add frequent renter points frequentrenterpoints ++; // add bonus for a two day new release rental if ((each.getmovie().getpricecode() == Movie.NEW_RELEASE)&& each.getdaysrented() > 1) frequentrenterpoints++; //show figures for this rental result += \t + each.getmovie().gettitle()+ \t + String.valueOf(each.getCharge()) + \n ; totalamount += each.getcharge(); // add footer lines result += Amount owed is +Sting.valueOf(totalAmount) + \n ; result += You earned +Sting.valueOf(frequentRenterPoints) + frequent renter points\n ; return result; 44

45 Refactoring: step 9 class Customer... public String statement() { double totalamount = 0; int frequentrenterpoints = 0; Enumeration rentals = _rental.elements(); String result = Rental Record for + getname() + \n ; while (rentals.hasmoreelements()) { Rental each = (Rental) rentals.nextelement(); frequentrenterpoints += each.getfrequentrenterpoints(); //show figures for this rental result += \t + each.getmovie().gettitle()+ \t + String.valueOf(each.getCharge()) + \n ; totalamount += each.getcharge(); // add footer lines result += Amount owed is +Sting.valueOf(totalAmount) + \n ; result += You earned +Sting.valueOf(frequentRenterPoints) + frequent renter points\n ; return result; 45

46 Refactoring: step 9 class Rental... public int getfrequentrenterpoints() { if ((getmovie().getpricecode() == Movie.NEW_RELEASE) && getdaysrented() > 1) return 2; else return 1; 46

47 Refactoring Sequence diagram before extraction and movement of the frequent renter points calculation 47

48 Refactoring Sequence diagram after extraction and movement of the frequent renter points calculation getfrequentrenterpoints() 48

49 Refactoring: step 10 Replace Temp with Query (the temporaries make the method complex and force code duplication) class Customer... public String statement() { double totalamount = 0; int frequentrenterpoints = 0; Enumeration rentals = _rental.elements(); String result = Rental Record for + getname() + \n ; while (rentals.hasmoreelements()) { Rental each = (Rental) rentals.nextelement(); frequentrenterpoints += each.getfrequentrenterpoints(); //show figures for this rental result += \t + each.getmovie().gettitle()+ \t + String.valueOf(each.getCharge()) + \n ; totalamount += each.getcharge(); // add footer lines result += Amount owed is +Sting.valueOf(totalAmount) + \n ; result += You earned +Sting.valueOf(frequentRenterPoints) + frequent renter points\n ; return result; 49

50 Refactoring: step 10 class Customer... public String statement() { int frequentrenterpoints = 0; Enumeration rentals = _rental.elements(); String result = Rental Record for + getname() + \n ; while (rentals.hasmoreelements()) { Rental each = (Rental) rentals.nextelement(); frequentrenterpoints += each.getfrequentrenterpoints(); //show figures for this rental result += \t + each.getmovie().gettitle()+ \t + String.valueOf(each.getCharge()) + \n ; // add footer lines result += Amount owed is +Sting.valueOf(getTotalCharge() gettotalcharge()) + \n ; result += You earned +Sting.valueOf(frequentRenterPoints)+ frequent renter points\n ; return result; 50

51 Refactoring: step 10 class Customer... private double gettotalcharge() { double result = 0; Enumeration rentals = _rentals.elements(); while (rentals.hasmoreelements()) { Rental each = (Rental) rentals.nextelement(); result += each.getcharge(); return result; 51

52 Refactoring: step 11 Replace Temp with Query class Customer... public String statement() { int frequentrenterpoints = 0; Enumeration rentals = _rental.elements(); String result = Rental Record for + getname() + \n ; while (rentals.hasmoreelements()) { Rental each = (Rental) rentals.nextelement(); frequentrenterpoints += each.getfrequentrenterpoints(); //show figures for this rental result += \t + each.getmovie().gettitle()+ \t + String.valueOf(each.getCharge()) + \n ; // add footer lines result += Amount owed is +Sting.valueOf(getTotalCharge()) + \n ; result += You earned +Sting.valueOf(frequentRenterPoints)+ frequent renter points\n ; return result; 52

53 Refactoring: step 11 Replace Temp with Query class Customer... public String statement() { Enumeration rentals = _rental.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 +Sting.valueOf(getTotalCharge()) + \n ; result += You earned +Sting.valueOf(getFrequentRenterPoints() getfrequentrenterpoints())+ frequent renter points\n ; return result; 53

54 Refactoring: step 11 class Customer... private double getfrequentrenterpoints() { double result = 0; Enumeration rentals = _rentals.elements(); while (rentals.hasmoreelements()) { return result; Rental each = (Rental) rentals.nextelement(); result += each.getfrequentrenterpoints(); 54

55 Diagrams after the Refactorings Movie PriceCode: int Rental 1 * daysrented: int * 1 getcharge() getfrequentrenterpoints() Customer Statement() acustomer arental amovie statement *[for all rentals] getcharge getpricecode getdaysrented getpricecode 55

56 Refactoring Remarks Most refactoring reduce code size, but this is not necessarily the case. The point is to make code easier to modify and more readable. Performance gets a hit by running the same loop three times, or does it? Profile the program and find the answer. 56

57 Software extension (Not Refactoring) The requested method can be added with minimal code duplication. (HTML string) class Customer... public String htmlstatement() { Enumeration rentals = _rental.elements(); String result = <H1>Rental Record for<em> + getname() + <EM></H1><P>\n ; while (rentals.hasmoreelements()) { Rental each = (Rental) rentals.nextelement(); //show figures for this rental result += each.getmovie().gettitle()+ : + String.valueOf(each.getCharge()) + <BR>\n ; // add footer lines result += <P>Amount owed is<em> +Sting.valueOf(getTotalCharge()) + </EM><P>\n ; result += You earned <EM> +Sting.valueOf(getFrequentRenterPoints() getfrequentrenterpoints())+ </EM> frequent renter points<p>\n ; return result; 57

58 A More General Approach Define a method object to encapsulate the statement method in the form of a new Statement class with TextStatement and HtmlStatement subclasses Rename statement method to value within the Statement classes and pass a Customer as argument Add getrentals method to return an Enumeration of current Rentals Relax visibility of gettotalcharge and gettotalfrequentrenterpoints 58

59 New functionality Getting ready to change the classification of the movies in the store. Perhaps new classification, perhaps modification to existing. Charging and frequent renting will be affected. 59

60 Refactoring: step 12 Replacing conditional logic (switch-case) on Price Code with OO polymorphism 60

61 Refactoring: step 12 Move getcharge from Rental to Movie class Rental... public double getcharge() { double result = 0; switch (getmovie().getpricecode()) { case Movie.REGULAR: result += 2; if (getdaysrented() > 2) result +=(getdaysrented()-2) * 1.5; break; case Movie.NEW_RELEASE: result += getdaysrented() * 3; break; case Movie.CHILDRENS: result += 1.5; if (getdaysrented() > 3) result +=(getdaysrented()-3) * 1.5; break; return result ; 61

62 Refactoring: step 12 class Movie... public double getcharge(int daysrented) { double result = 0; switch (getpricecode()) { case REGULAR: result += 2; if (getdaysrented() > 2) break; case NEW_RELEASE: result +=(getdaysrented()-2) * 1.5; result += getdaysrented() * 3; break; case CHILDRENS: return result ; result += 1.5; if (getdaysrented() > 3) break; result +=(getdaysrented()-3) * 1.5; 62

63 Refactoring: step 12 class Rental... public double getcharge() { return _movie.getcharge(_daysrented); 63

64 Refactoring: step 13 Move getfrequentrenterpoints() to Movie class Rental... public int getfrequentrenterpoints() { if ((getmovie().getpricecode() == Movie.NEW_RELEASE) else && getdaysrented() > 1) return 2; return 1; 64

65 Refactoring: step 13 class Movie... public int getfrequentrenterpoints(int daysrented) { if ((getpricecode() == Movie.NEW_RELEASE) && daysrented > 1) else return 2; return 1; class Rental... public int getfrequentrenterpoints() { return _movie.getfrequentrenterpoints(_daysrented); 65

66 Refactoring: Using Inheritance Inheritance among movie classes Won t work. A movie can change its classification during its lifetime. But an object cannot change its class! Movie getcharge getfrequent ChildrensMovie getcharge RegularMovie getcharge NewRelease getcharge getfrequent 66

67 Refactoring Using Patterns State/Strategy patterns A movie has a price object Movie PriceCode: int getcharge getfrequent 1 Price getcharge getfrequent ChildrensPrice getcharge RegularPrice getcharge NewReleasePrice getcharge getfrequent 67

68 Movie PriceCode: int getcharge getfrequent Replace Type Code with State/Strategy 1 Price getcharge getfrequent 1 ChildrensPrice RegularPrice getcharge getcharge NewReleasePrice getcharge getfrequent Rental daysrented: int getcharge() getfrequent * Customer Name: String Statement() htmlstatement() 68

69 Refactoring: step 14 Replace Type Code with State/Strategy class Movie... public Movie(String name, int pricecode) { _name = name; _pricecode = pricecode; 69

70 Refactoring: step 14 class Movie... public Movie(String name, int pricecode) { _name = name; setpricecode(pricecode); 70

71 Refactoring: step 14 abstract class Price { abstract int getpricecode(); class ChildrenPrice extends Price { int getpricecode(){ return MOVIE.CHILDREN; class NewReleasePrice extends Price { int getpricecode(){ return MOVIE.NEW_RELEASE; class RegularPrice extends Price { int getpricecode(){ return MOVIE.REGULAR; 71

72 Refactoring: step 15 class Movie... public int getpricecode() { return _pricecode; public void setpricecode(int arg) { _pricecode = arg; private int _pricecode; 72

73 Refactoring: step 15 class Movie... public int getpricecode() { return _price.getpricecode; public void setpricecode(int arg) { switch (arg) { case REGULAR: _price = new RegularPrice(); break; case CHILDREN: _price = new ChildrenPrice(); break; case NEW_RELEASE: _price = new NewReleasePrice(); break; default: throw new IllegalArgumentException( Incorrect Incorrect Price Code ); private Price _price; 73

74 Refactoring: step 16 Move Method: move switch-case to a method class Movie... public double getcharge(int daysrented) { double result = 0; switch (getpricecode()) { case REGULAR: result += 2; if (getdaysrented() > 2) result +=(getdaysrented()-2) * 1.5; break; case NEW_RELEASE: result += getdaysrented() * 3; break; case CHILDRENS: result += 1.5; if (getdaysrented() > 3) result +=(getdaysrented()-3) * 1.5; break; return result ; 74

75 Refactoring: step 16 class Movie... public double getcharge(int daysrented) { return _price.getcharge(daysrented); 75

76 Refactoring: step 16 Replace Conditional with Polymorphism class Price... double getcharge(int daysrented) { double result = 0; switch (getpricecode()) { case MOVIE.REGULAR: result += 2; if (getdaysrented() > 2) result +=(getdaysrented()-2) * 1.5; break; case MOVIE.NEW_RELEASE: result += getdaysrented() * 3; break; case MOVIE.CHILDRENS: result += 1.5; if (getdaysrented() > 3) result +=(getdaysrented()-3) * 1.5; break; return result ; 76

77 Refactoring: step 16 class RegularPrice... double getcharge(int daysrented) { double result = 2; if (getdaysrented() > 2) result +=(getdaysrented()-2) * 1.5; return result; class NewReleasePrice... double getcharge(int daysrented) { return daysrented * 3; class ChildrenPrice... double getcharge(int daysrented) { double result = 1.5; if (getdaysrented() > 3) result +=(getdaysrented()-3) * 1.5; return result ; class Price... abstract double getcharge(int daysrented); Three kinds of Prices 77

78 Refactoring: step 17 Replace Conditional with Polymorphism class Rental... int getfrequentrenterpoints(int daysrented) { if ((getpricecode() == Movie.NEW_RELEASE) && daysrented > 1) else return 2; return 1; 78

79 Refactoring: step 17 class Movie... int getfrequentrenterpoints(int daysrented) { return _price.getfrequentrenterpoints(daysrented); class Price... int getfrequentrenterpoints(int daysrented) { return 1; class NewReleasePrice.. int getfrequentrenterpoints(int daysrented) { //override return (daysrented > 1)? 2:1; 79

80 Refactoring Principles Why do we refactor? To improve the design of software To make software easier to understand To help you find bugs To make you program faster When should we refactor? 1. Refactor when you add functionality 2. Refactor when you need to fix a bug 3. Refactor as you do code reviews Refactor when the code starts to smell. What about performance? What about performance? Worry about performance only when you have identified a performance problem 80

81 Effective refactoring Use unit testing Test -> Refactor -> Test Use automated refactoring tools (e.g., Eclipse) Don t twiddle manually Plan your refactoring ahead of time Complex software requires complex refacotring planning 81

82 Eclipse & Refactoring 82

83 Some Bad Code Smells 83

84 Bad Smells in Code If it stinks, change it. --Grandma Beck on child rearing Duplicated Code (stench 10) If the same code structure is repeated Extract Method- gather duplicated code Pull Up Field - move to a common parent Form Template Method - gather similar parts, leaving holes Substitute Algorithm - choose the clearer algorithm Extract class - for unrelated classes, create a new class with functionality 84

85 Duplication: Example #1 public boolean save() throws IOException{ if (outputfile == null) {return false; FileWriter write = new FileWriter(outputFile); movies.writeto(writer); writer.close(); return true; public boolean saveas() throws IOException{ outputfile = view.getfile(); if (outputfile == null) {return false; FileWriter write = new FileWriter(outputFile); movies.writeto(writer); writer.close(); return true; 85

86 Duplication: Example #2 public class MovieList { private int numberofmovies = 0; private Collection movies = new ArrayList(); public size() { return movies.size(); public void add(movie movietoadd){ movies.add(movietoadd); numberofmovies++; 86

87 Duplication: Example #2 - cont public class MovieList { private int numberofmovies = 0; // delete private Collection movies = new ArrayList(); public size() { return movies.size(); public void add(movie movietoadd){ movies.add(movietoadd); numberofmovies++; //delete 87

88 Bad Smells in Code Long Method (stench 7) If the body of a method is over a page (choose your page size) Extract Method - extract related behavior Replace Temp with Query - remove temporaries when they obscure meaning Introduce Parameter Object - slim down parameter lists by making them into objects Replace Method with Method Object - still too many parameters Decompose Conditionals - conditional and loops can be moved to their own methods 88

89 Bad Smells in Code Large Class (stench 7) If a class has either too many variables or too many methods Extract Class- to bundle variables/methods 89

90 Bad Smells in Code Long Parameter List (stench 6) A method does not need many parameter, only enough to be able to retrieve what it needs Replace Parameter with Method - turn a parameter into a message Introduce Parameter Object - turn several parameters into an object Example: Replace public void marry(string name, int age, boolean gender, String name2, int age2, boolean gender2) {... with public void marry(person person1, Person person2) {... 90

91 Bad Smells in Code Divergent Change (stench 5) If you find yourself repeatedly changing the same class then there is probably something wrong with it Extract Class - group functionality commonly changed into a class 91

92 Bad Smells in Code Switch Statements (stench 5) Switch statements lead to duplication and inhibit change Extract method -to remove the switch Move method - to get the method where polymorphism can apply Replace Type Code with State/Strategy -set up inheritance Replace Conditional with Polymorphism - get rid of the switch 92

93 Bad Smells in Code Feature Envy (stench 6) If a method seems more interested in a class other than the class it actually is in Move Method - move the method to the desired class Extract Method - if only part of the method shows the symptoms 93

94 Bad Smells in Code Parallel Inheritance Hierarchies (stench 6) If when ever you make a subclass in one corner of the hierarchy, you must create another subclass in another corner Move Method/Field - get one hierarchy to refer to the other 94

95 Bad Smells in Code Lazy Class (stench 4) If a class (e.g. after refactoring) does not do much, eliminate it. Collapse Hierarchy- for subclasses Inline Class - remove a single class 95

96 Bad Smells in Code Temporary Field (stench 3) If a class has fields that are only set in special cases, extract them Extract Class- for the special fields 96

97 Bad Smells in Code Message Chains (stench 3) BazObject b =foo.getbar().getbaz() Long chains of messages to get to a value are brittle as any change in the intermittent structure will break the code Hide Delegate - remove one link in a chain Extract Method - change the behavior to avoid chains As an example of Hide Delegate, we can introduce the following method into foo s class: BazObject getbaz() { return bar.getbaz(); And then we can just call BazObject b = foo.getbaz(); 97

98 Bad Smells in Code Middle Man (stench 3) An intermediary object is used too often to get at encapsulated values Remove Middle Man - to talk directly to the target Replace Delegation with Inheritance - turns the middle man into a subclass of the real object 98

99 Bad Smells in Code Inappropriate Intimacy (stench 5) Classes may make too much use of each other s fields and methods Move Method/Field - to separate pieces in order to reduce intimacy Extract Class - make a common class of shared behavior/data Replace Inheritance with Delegation -when a subclass is getting too cozy 99

100 Bad Code Smells: Inappropriate Intimacy // class Movielist public void writeto(writer destination) throws IOException{ Iterator movieiterator = movies.iterator(); while movieiterator.hasnext()) { Movie movietowrite = (Movie)movieIterator.next(); destination.write(movietowrite.getname()); destination.write( ); destination.write(movietowrite.getcategory().tostring()); destination.write( ); try{ destination.write(integer.tostring(movietowrite.getrating())); catch (UnratedException ex) { destination.write( -1 ); destination.write( \n ); 100

101 Bad Code Smells Inappropriate Intimacy A class knows too much about another s internal details WriteTo in MovieList has and uses full knowledge of the structure of Movie If the structure of Movie changes (e.g. multiple ratings), WriteTo in MovieList must change to match Move the loop body into a new writeto method in Movie // class Movielist public void writeto(writer destination) throws IOException{ Iterator movieiterator = movies.iterator(); while movieiterator.hasnext()) { Movie movietowrite = (Movie)movieIterator.next(); movietowrite.writeto(destination); 101

102 The rule of three (XP) The first time you code a task, just do it. The second time you code the same idea, wince and code it up again. The third time you code the same idea, it s time to refactor! Any programming construct can be made more abstract but that s not necessarily a good thing. Generality (flexibility) costs too Don t spin you wheels designing and coding the most abstract system you can imagine. Practise Just-in-Time abstraction. Expect that you will be re-arranging your code constantly. Don t worry about it. Embrace it. 102

Refactoring. In essence we improve the design of the code after it has been written. That's an odd turn of phrase.

Refactoring. In essence we improve the design of the code after it has been written. That's an odd turn of phrase. Refactoring Process of changing software in such a way that it does not alter the external behavior of the code yet improves its internal structure. Disciplined way to clean up code that minimizes the

More information

Refactoring: Improving the Design of Existing Code

Refactoring: Improving the Design of Existing Code Refactoring: Improving the Design of Existing Code Martin Fowler fowler@acm.org www.martinfowler.com www.thoughtworks.com What is Refactoring A series of small steps, each of which changes the program

More information

Software Engineering Refactoring

Software Engineering Refactoring Software Engineering Refactoring Software Engineering 2012-2013 Department of Computer Science Ben-Gurion university Based on slides of: Mira Balaban Department of Computer Science Ben-Gurion university

More information

Code Refactoring. CS356 Object-Oriented Design and Programming November 21, 2014

Code Refactoring. CS356 Object-Oriented Design and Programming   November 21, 2014 Code Refactoring CS356 Object-Oriented Design and Programming http://cs356.yusun.io November 21, 2014 Yu Sun, Ph.D. http://yusun.io yusun@csupomona.edu The Problem: Software Drift Over many phases of maintenance,

More information

Refactoring. Chen Tang March 3, 2004

Refactoring. Chen Tang March 3, 2004 Refactoring Chen Tang March 3, 2004 What Is Refactoring (Definition) Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet

More information

Refactoring, Part 2. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 27 12/01/09. University of Colorado, 2009

Refactoring, Part 2. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 27 12/01/09. University of Colorado, 2009 Refactoring, Part 2 Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 27 12/01/09 University of Colorado, 2009 1 Introduction Credit where Credit is Due Some of the material for

More information

Refactoring Exercise

Refactoring Exercise Refactoring Exercise Maria Grazia Pia INFN Genova, Italy Maria.Grazia.Pia@cern.ch http://www.ge.infn.it/geant4/training/apc2017/ Exercise: The Video Store Grab basic concepts Get into the habit of refactoring

More information

CS247. Today s topics. Design matters. What is refactoring?

CS247. Today s topics. Design matters. What is refactoring? Today s topics CS247 Refactoring Adapted from Martin Fowler s text and Mike Godfrey s slides. What is refactoring and why do we care? The rule of three. A simple case study that applies some refactorings.

More information

Example of OO Design Refactoring

Example of OO Design Refactoring Example of OO Design Refactoring Robert B. France Colorado State University Fort Collins Colorado Robert B. France 1 What is design refactoring? Often an initial design is not a good design Design may

More information

Introduction to Refactoring

Introduction to Refactoring Introduction to Refactoring Sutee Sudprasert 1 Credits Refactoring : Improving the design of existing code - Martin Fowler Design Patterns - GOF 2 What is refactoring? Refactoring is the process of changing

More information

void printowing(double amount) { printbanner(); printdetails(); void printdetails(double amount) {

void printowing(double amount) { printbanner(); printdetails(); void printdetails(double amount) { Refactoring References: Martin Fowler, Refactoring: Improving the Design of Existing Code; ; Bruce Wampler, The Essence of Object-Oriented Oriented Programming with Java and UML A recent OO technique that

More information

Refactoring. Software Engineering, DVGC18 Faculty of Economic Sciences, Communication and IT Eivind Nordby

Refactoring. Software Engineering, DVGC18 Faculty of Economic Sciences, Communication and IT Eivind Nordby Refactoring Faculty of Economic Sciences, Communication and IT 2011-09-21 Why Refactor Refactoring is one factor in keeping your system in shape Without continuous refactoring, the system will rot It takes

More information

AntiPatterns. EEC 421/521: Software Engineering. AntiPatterns: Structure. AntiPatterns: Motivation

AntiPatterns. EEC 421/521: Software Engineering. AntiPatterns: Structure. AntiPatterns: Motivation AntiPatterns EEC 421/521: Software Engineering Definition: An AntiPattern describes a commonly occurring solution to a problem that generates decidedly negative consequences Refactoring Reference: Refactoring

More information

Refactoring 101. By: Adam Culp

Refactoring 101. By: Adam Culp By: Adam Culp Twitter: @adamculp https://joind.in/14927 2 About me PHP 5.3 Certified Consultant at Zend Technologies Organizer SoFloPHP (South Florida) Organized SunshinePHP (Miami) Long distance (ultra)

More information

Objectives: On completion of this project the student should be able to:

Objectives: On completion of this project the student should be able to: ENGI-0655/5232 Software Construction and Evolution Project 1 Reverse Engineering Refactoring & Object Oriented Design Due date November 10, 2009-4:00 pm 1. Aims The aim of this project is to give you more

More information

Credit where Credit is Due. Lecture 25: Refactoring. Goals for this lecture. Last Lecture

Credit where Credit is Due. Lecture 25: Refactoring. Goals for this lecture. Last Lecture Credit where Credit is Due Lecture 25: Refactoring Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 6448 - Spring Semester, 2002 Some of the material for this lecture and lecture 26 is taken

More information

On the automation of challenging refactorings through advanced method extraction techniques

On the automation of challenging refactorings through advanced method extraction techniques On the automation of challenging refactorings through advanced method extraction techniques Ran Ettinger (RanE@il.ibm.com), IBM Haifa Research Lab In Software Engineering Course, Ben-Gurion University

More information

On the automation of challenging refactorings through advanced method extraction techniques

On the automation of challenging refactorings through advanced method extraction techniques On the automation of challenging refactorings through advanced method extraction techniques Ran Ettinger (RanE@il.ibm.com, https://researcher.ibm.com/researcher/view.php?person=il-rane) IBM Research Haifa

More information

Patterns in Software Engineering

Patterns in Software Engineering Patterns in Software Engineering Lecturer: Raman Ramsin Lecture 10 Refactoring Patterns Part 1 1 Refactoring: Definition Refactoring: A change made to the internal structure of software to make it easier

More information

PRÁCTICO 1: MODELOS ESTÁTICOS INGENIERÍA INVERSA DIAGRAMAS DE CLASES

PRÁCTICO 1: MODELOS ESTÁTICOS INGENIERÍA INVERSA DIAGRAMAS DE CLASES PRÁCTICO 1: MODELOS ESTÁTICOS INGENIERÍA INVERSA DIAGRAMAS DE CLASES Una parte importante dentro del proceso de re-ingeniería de un sistema es la ingeniería inversa del mismo, es decir, la obtención de

More information

What? reorganising its internal structure

What? reorganising its internal structure What? Improving a computer program by reorganising its internal structure without t altering its external behaviour. (http://dictionary.reference.com/browse/refactoring ) Why? Improves the over all design

More information

McCa!"s Triangle of Quality

McCa!s Triangle of Quality McCa!"s Triangle of Quality Maintainability Portability Flexibility Reusability Testability Interoperability PRODUCT REVISION PRODUCT TRANSITION PRODUCT OPERATION Correctness Usability Reliability Efficiency

More information

MSO Refactoring. Hans Philippi. October 2, Refactoring 1 / 49

MSO Refactoring. Hans Philippi. October 2, Refactoring 1 / 49 MSO Refactoring Hans Philippi October 2, 2018 Refactoring 1 / 49 This lecture What is refactoring?... or how to deal with the horrible code your colleagues have created... or how to deal with the horrible

More information

INF5120 Modellbasert Systemutvikling. F10-2: Architectural Patterns, Design Patterns and Refactoring. Lecture Arne-Jørgen Berre

INF5120 Modellbasert Systemutvikling. F10-2: Architectural Patterns, Design Patterns and Refactoring. Lecture Arne-Jørgen Berre INF5120 Modellbasert Systemutvikling F10-2: Architectural Patterns, Design Patterns and Refactoring Lecture 28.03.2011 2011 Arne-Jørgen Berre Patterns: From Analysis to Implementation Analysis Design Implementation

More information

Refactoring. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 27 11/29/11. University of Colorado, 2011

Refactoring. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 27 11/29/11. University of Colorado, 2011 Refactoring Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 27 11/29/11 University of Colorado, 2011 Credit where Credit is Due Some of the material for this lecture is taken

More information

INF5120 Modellbasert Systemutvikling

INF5120 Modellbasert Systemutvikling INF5120 Modellbasert Systemutvikling F07-2: Architectural Patterns, Design Patterns and Refactoring Lecture 27.02.2017 Arne-Jørgen Berre Patterns: From Analysis to Implementation Analysis Design Implementation

More information

Administrivia. Programming Language Fall Example. Evolving Software. Project 3 coming out Midterm October 28. Refactoring October 14, 2004

Administrivia. Programming Language Fall Example. Evolving Software. Project 3 coming out Midterm October 28. Refactoring October 14, 2004 CMSC 433 Programming Language Fall 2004 Project 3 coming out Midterm October 28 Administrivia Refactoring October 14, 2004 Lots of material taken from Fowler, Refactoring: Improving the Design of Existing

More information

Evolving Software. CMSC 433 Programming Language Technologies and Paradigms Spring Example. Some Motivations for This Refactoring

Evolving Software. CMSC 433 Programming Language Technologies and Paradigms Spring Example. Some Motivations for This Refactoring CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Refactoring April 24, 2007 Lots of material taken from Fowler, Refactoring: Improving the Design of Existing Code 1 Evolving Software

More information

Refactoring, 2nd Ed. A love story. Michael Hunger

Refactoring, 2nd Ed. A love story. Michael Hunger Refactoring, 2nd Ed. A love story Michael Hunger Michael Hunger Open Sourcerer Neo4j @mesirii It crashed at 940! I know what you're here for! Covers By: dev.to/rly Which Refactoring do you like most? Extract

More information

Refactoring. George Dinwiddie idia Computing, LLC

Refactoring. George Dinwiddie idia Computing, LLC Refactoring George Dinwiddie idia Computing, LLC http://idiacomputing.com http://blog.gdinwiddie.com What is Refactoring? Refactoring is a disciplined technique for restructuring an existing body of code,

More information

Composing Methods. Extract Method - Code that can be grouped - Meaningful name for method

Composing Methods. Extract Method - Code that can be grouped - Meaningful name for method Composing Methods Extract Method - Code that can be grouped - Meaningful name for method Inline Method - inverse of Extract Method - Method body is more obvious Extract Variable - Expression: hard to understand

More information

JUnit 3.8.1, 64. keep it simple stupid (KISS), 48

JUnit 3.8.1, 64. keep it simple stupid (KISS), 48 Index A accessor methods, 11, 152 add parameter technique, 189 190 add() method, 286 287, 291 algorithm, substituting, 104 105 AND logical operator, 172 architectural design patterns, 277 278 architecture,

More information

More on Design. CSCI 5828: Foundations of Software Engineering Lecture 23 Kenneth M. Anderson

More on Design. CSCI 5828: Foundations of Software Engineering Lecture 23 Kenneth M. Anderson More on Design CSCI 5828: Foundations of Software Engineering Lecture 23 Kenneth M. Anderson Outline Additional Design-Related Topics Design Patterns Singleton Strategy Model View Controller Design by

More information

Software Design COSC 4353/6353 D R. R A J S I N G H

Software Design COSC 4353/6353 D R. R A J S I N G H Software Design COSC 4353/6353 D R. R A J S I N G H Week 5 Refactoring What is Refactoring? Code Smells Why Refactoring? Techniques IDEs What is Refactoring? Art of improving the design of existing code

More information

Refactorings. Refactoring. Refactoring Strategy. Demonstration: Refactoring and Reverse Engineering. Conclusion

Refactorings. Refactoring. Refactoring Strategy. Demonstration: Refactoring and Reverse Engineering. Conclusion Refactorings Refactoring What is it? Why is it necessary? Examples Tool support Refactoring Strategy Code Smells Examples of Cure Demonstration: Refactoring and Reverse Engineering Refactor to Understand

More information

COURSE 11 DESIGN PATTERNS

COURSE 11 DESIGN PATTERNS COURSE 11 DESIGN PATTERNS PREVIOUS COURSE J2EE Design Patterns CURRENT COURSE Refactoring Way refactoring Some refactoring examples SOFTWARE EVOLUTION Problem: You need to modify existing code extend/adapt/correct/

More information

Refactoring. Paul Jackson. School of Informatics University of Edinburgh

Refactoring. Paul Jackson. School of Informatics University of Edinburgh Refactoring Paul Jackson School of Informatics University of Edinburgh Refactoring definition Refactoring (noun) is a change made to the internal structure of software to make it easier to understand,

More information

Refactoring. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 27 04/19/11. University of Colorado, 2011

Refactoring. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 27 04/19/11. University of Colorado, 2011 Refactoring Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 27 04/19/11 University of Colorado, 2011 Credit where Credit is Due Some of the material for this lecture is taken

More information

F. Tip and M. Weintraub REFACTORING. Thanks go to Andreas Zeller for allowing incorporation of his materials

F. Tip and M. Weintraub REFACTORING. Thanks go to Andreas Zeller for allowing incorporation of his materials F. Tip and M. Weintraub REFACTORING Thanks go to Andreas Zeller for allowing incorporation of his materials TODAY S LECTURE anti-patterns common response to a recurring problem that is usually ineffective

More information

MSO Lecture 6. Wouter Swierstra. September 24, 2015

MSO Lecture 6. Wouter Swierstra. September 24, 2015 1 MSO Lecture 6 Wouter Swierstra September 24, 2015 2 LAST LECTURE Case study: CAD/CAM system What are design patterns? Why are they important? What are the Facade and Adapter patterns? 3 THIS LECTURE

More information

Refactoring. Refactoring Techniques

Refactoring. Refactoring Techniques Refactoring Refactoring Techniques Code Quality is Important! Refactoring is... A disciplined technique for restructuring an existing body of code, altering its internal structure without changing its

More information

CSE 403 Lecture 21. Refactoring and Code Maintenance. Reading: Code Complete, Ch. 24, by S. McConnell Refactoring, by Fowler/Beck/Brant/Opdyke

CSE 403 Lecture 21. Refactoring and Code Maintenance. Reading: Code Complete, Ch. 24, by S. McConnell Refactoring, by Fowler/Beck/Brant/Opdyke CSE 403 Lecture 21 Refactoring and Code Maintenance Reading: Code Complete, Ch. 24, by S. McConnell Refactoring, by Fowler/Beck/Brant/Opdyke slides created by Marty Stepp http://www.cs.washington.edu/403/

More information

MSO Lecture 6. Wouter Swierstra (adapted by HP) September 28, 2017

MSO Lecture 6. Wouter Swierstra (adapted by HP) September 28, 2017 1 MSO Lecture 6 Wouter Swierstra (adapted by HP) September 28, 2017 2 LAST LECTURE Case study: CAD/CAM system What are design patterns? Why are they important? What are the Facade and Adapter patterns?

More information

Small changes to code to improve it

Small changes to code to improve it Small changes to code to improve it 1 Refactoring Defined A change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior

More information

How We Refactor, and How We Know It

How We Refactor, and How We Know It Emerson Murphy-Hill, Chris Parnin, Andrew P. Black How We Refactor, and How We Know It Urs Fässler 30.03.2010 Urs Fässler () How We Refactor, and How We Know It 30.03.2010 1 / 14 Refactoring Definition

More information

Refactoring. Section (JIA s) OTHER SOURCES

Refactoring. Section (JIA s) OTHER SOURCES Refactoring Section 7.2.1 (JIA s) OTHER SOURCES Code Evolution Programs evolve and code is NOT STATIC Code duplication Outdated knowledge (now you know more) Rethink earlier decisions and rework portions

More information

Lecture Notes. Polymorphism. Polymorphism. If Polymorphism is Not Available. To be placed at:

Lecture Notes. Polymorphism. Polymorphism. If Polymorphism is Not Available. To be placed at: To be placed at: Lecture Notes www.cs.umb.edu/~jxs/courses/cs40 Polymorphism Polymorphism If Polymorphism is Not Available Customer gettotaltax():float * Account accounts # balance: float getbalance():

More information

Implementing evolution: Refactoring

Implementing evolution: Refactoring 2IS55 Software Evolution Sources Implementing evolution: Refactoring Alexander Serebrenik / SET / W&I 17-5-2010 PAGE 1 Last week Problem: changing code is difficult Assignment 6 Deadline: Today Assignment

More information

The Benefits And Reasons for Doing Refactoring

The Benefits And Reasons for Doing Refactoring The Benefits And Reasons for Doing Refactoring CSC508 Software Engineering by Magnus Aase December 11, 2001 The people behind the work of Refactoring seem all to agree on that Refactoring is not a cure

More information

Kerievsky_book.fm Page 355 Thursday, July 8, :12 PM. Index

Kerievsky_book.fm Page 355 Thursday, July 8, :12 PM. Index Kerievsky_book.fm Page 355 Thursday, July 8, 2004 12:12 PM Index A Absorbing class, 117 Abstract Factory, 70 71 Accept methods, 327 Accumulation methods, 315, 325 330 Accumulation refactorings Collecting

More information

Badge#8: Geek Refactoring

Badge#8: Geek Refactoring Badge#8: Geek Refactoring Nuno Pombo, Qualidade de Software, 2018/19 1 When To Refactor? Rule of Three When adding a feature When fixing a bug During a code review 2 How To Refactor? The code should become

More information

Hugbúnaðarverkefni 2 - Static Analysis

Hugbúnaðarverkefni 2 - Static Analysis Time to do some refactoring of my Java. Hugbúnaðarverkefni 2 - Static Analysis Fyrirlestrar 7 & 8 A Refactoring Micro-Example 15/01/2006 Dr Andy Brooks 1 Case Study Dæmisaga Reference A Refactoring Micro-Example,

More information

Refactoring. Herez Moise Kattan NUSP: João S. Brito Júnior NUSP:

Refactoring. Herez Moise Kattan NUSP: João S. Brito Júnior NUSP: Refactoring Herez Moise Kattan NUSP: 9860455 João S. Brito Júnior NUSP: 5889672 1 Definition Refactoring is the process of changing a software system in such a way that it does not* alter the external

More information

SOFTWARE ENGINEERING SOFTWARE EVOLUTION. Saulius Ragaišis.

SOFTWARE ENGINEERING SOFTWARE EVOLUTION. Saulius Ragaišis. SOFTWARE ENGINEERING SOFTWARE EVOLUTION Saulius Ragaišis saulius.ragaisis@mif.vu.lt CSC2008 SE Software Evolution Learning Objectives: Identify the principal issues associated with software evolution and

More information

Designing with patterns - Refactoring. What is Refactoring?

Designing with patterns - Refactoring. What is Refactoring? Designing with patterns - Refactoring Bottom up based application of patterns Improving the design after it has been written What is Refactoring? Two definitions, the object and act of change in software

More information

Understading Refactorings

Understading Refactorings Understading Refactorings Ricardo Terra terra@dcc.ufmg.br Marco Túlio Valente mtov@dcc.ufmg.br UFMG, 2010 UFMG, 2010 Understanding Refactorings 1 / 36 Agenda 1 Overview 2 Refactoring 3 Final Considerations

More information

Restructuring. What is restructuring? Tudor Gîrba Reengineering life cycle. What? forward engineering. reverse engineering

Restructuring. What is restructuring? Tudor Gîrba   Reengineering life cycle. What? forward engineering. reverse engineering Restructuring Tudor Gîrba www.tudorgirba.com Reengineering life cycle Reengineering... is the examination and alteration of a subject system to reconstitute it in a new form and the subsequent implementation

More information

CSE 70 Final Exam Fall 2009

CSE 70 Final Exam Fall 2009 Signature cs70f Name Student ID CSE 70 Final Exam Fall 2009 Page 1 (10 points) Page 2 (16 points) Page 3 (22 points) Page 4 (13 points) Page 5 (15 points) Page 6 (20 points) Page 7 (9 points) Page 8 (15

More information

MSO Exam November 7, 2016, 13:30 15:30, Educ-Gamma

MSO Exam November 7, 2016, 13:30 15:30, Educ-Gamma MSO 2016 2017 Exam November 7, 2016, 13:30 15:30, Educ-Gamma Name: Student number: Please read the following instructions carefully: Fill in your name and student number above. Be prepared to identify

More information

Code Smells & Refactoring

Code Smells & Refactoring Material and some slide content from: - Mehdi Amoui Kalareh - Fowler Refactoring book Code Smells & Refactoring Reid Holmes Lecture 18 - Tuesday November 22 2011. Program restructuring Software systems

More information

Keywords Code clean up, code standard, maintainability, extendibility, software refactoring, bad smell code.

Keywords Code clean up, code standard, maintainability, extendibility, software refactoring, bad smell code. Volume 7, Issue 5, May 2017 ISSN: 2277 128X International Journal of Advanced Research in Computer Science and Software Engineering Research Paper Available online at: www.ijarcsse.com A Review on Bad

More information

SEEM4570 System Design and Implementation. Lecture 11 From Design to Implementation

SEEM4570 System Design and Implementation. Lecture 11 From Design to Implementation SEEM4570 System Design and Implementation Lecture 11 From Design to Implementation Introduction We learned programming and we learned UML, but separately. Now, the question is how can we translate a design

More information

11/2/09. Code Critique. What goal are we designing to? What is the typical fix for code smells? Refactoring Liskov Substitution Principle

11/2/09. Code Critique. What goal are we designing to? What is the typical fix for code smells? Refactoring Liskov Substitution Principle Code Critique Identifying smells Refactoring Liskov Substitution Principle What goal are we designing to? What is the typical fix for code smells? What is a limitation of those fixes? How do we address

More information

כללי Extreme Programming

כללי Extreme Programming פיתוח מער כות תוכנה מבוססות Java כללי Extreme Programming אוהד ברזילי ohadbr@tau.ac.il Based on: K. Beck: Extreme Programming Explained. E. M. Burke and B.M. Coyner: Java Extreme Programming Cookbook.

More information

DAT159 Refactoring (Introduction)

DAT159 Refactoring (Introduction) DAT159 Refactoring (Introduction) Volker Stolz 1, with contributions by: Larissa Braz 2, Anna M. Eilertsen 3, Fernando Macías 1, Rohit Gheyi 2 Western Norway University of Applied Sciences, Universidade

More information

Refactoring. What to refactor Refactor to what How to conduct the refactoring. This website is also very informative

Refactoring. What to refactor Refactor to what How to conduct the refactoring. This website is also very informative Refactoring What to refactor Refactor to what How to conduct the refactoring This website is also very informative https://refactoring.com/catalog/ Definitions Changing/improving the code structure w/o

More information

CSCD01 Engineering Large Software Systems. Refactoring. Joe Bettridge. Winter With thanks to Anya Tafliovich (Based on Refactoring by M.

CSCD01 Engineering Large Software Systems. Refactoring. Joe Bettridge. Winter With thanks to Anya Tafliovich (Based on Refactoring by M. CSCD01 Engineering Large Software Systems Refactoring Joe Bettridge Winter 2018 With thanks to Anya Tafliovich (Based on Refactoring by M. Fowler) What is Refactoring? Process of changing a software system

More information

PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 10. PUTTING IT ALL TOGETHER. Are we there yet?

PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 10. PUTTING IT ALL TOGETHER. Are we there yet? PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 10. PUTTING IT ALL TOGETHER Are we there yet? Developing software, OOA&D style You ve got a lot of new tools, techniques, and ideas about how to develop

More information

Code Smells & Refactoring

Code Smells & Refactoring Material and some slide content from: - Mehdi Amoui Kalareh SERVICES COMPONENTS OBJECTS MODULES Code Smells & Refactoring Reid Holmes Lecture 21 - Thursday November 25 2010. Program restructuring Software

More information

Reengineering II. Transforming the System

Reengineering II. Transforming the System Reengineering II Transforming the System Recap: Reverse Engineering We have a detailed impression of the current state We identified the important parts We identified reengineering opportunities We have

More information

MSO Lecture 9. Wouter Swierstra (adapted by HP, AL) October 12, 2017

MSO Lecture 9. Wouter Swierstra (adapted by HP, AL) October 12, 2017 1 MSO Lecture 9 Wouter Swierstra (adapted by HP, AL) October 12, 2017 2 BEFORE WE START... Some notes on Kahoot! nicknames: Normaal: Anneke, Bastiaan, Pieter, Sjaak, Ruud,... Funny: Jeroen Fokker, Sergey

More information

CPSC 310 Software Engineering. Lecture 11. Design Patterns

CPSC 310 Software Engineering. Lecture 11. Design Patterns CPSC 310 Software Engineering Lecture 11 Design Patterns Learning Goals Understand what are design patterns, their benefits and their drawbacks For at least the following design patterns: Singleton, Observer,

More information

Refactoring with Eclipse

Refactoring with Eclipse Refactoring with Eclipse Seng 371 Lab 8 By Bassam Sayed Based on IBM article Explore refactoring functions in Eclipse JDT by Prashant Deva Code Refactoring Code refactoring is a disciplined way to restructure

More information

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

bright code, dull code by fox \

bright code, dull code by fox \ bright code, dull code by fox peterson @a_fox_box \ Can you think of a time you ve been here? You come across a piece of code, you are expected to be able to work with it, and you re thinking I DIDN T

More information

Object-Oriented Design

Object-Oriented Design Object-Oriented Design Lecture 14: Design Workflow Department of Computer Engineering Sharif University of Technology 1 UP iterations and workflow Workflows Requirements Analysis Phases Inception Elaboration

More information

Software Design and Analysis CSCI 2040

Software Design and Analysis CSCI 2040 Software Design and Analysis CSCI 2040 Introduce two important development practices in the context of the case studies: Test-Driven Development Refactoring 2 Logic is the art of going wrong with confidence

More information

COURSE 2 DESIGN PATTERNS

COURSE 2 DESIGN PATTERNS COURSE 2 DESIGN PATTERNS CONTENT Fundamental principles of OOP Encapsulation Inheritance Abstractisation Polymorphism [Exception Handling] Fundamental Patterns Inheritance Delegation Interface Abstract

More information

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L Inheritance Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 9.4 1 Inheritance Inheritance allows a software developer to derive

More information

Implementing evolution: Refactoring

Implementing evolution: Refactoring 2IS55 Software Evolution Implementing evolution: Refactoring Alexander Serebrenik Sources / SET / W&I 5-6-2012 PAGE 1 Last week How to implement evolution Last week: evolution strategies and decision making

More information

Tackling Design Patterns Chapter 3: Template Method design pattern and Public Inheritance. 3.1 Introduction... 2

Tackling Design Patterns Chapter 3: Template Method design pattern and Public Inheritance. 3.1 Introduction... 2 Department of Computer Science Tackling Design Patterns Chapter 3: Template Method design pattern and Public Inheritance Copyright c 2016 by Linda Marshall and Vreda Pieterse. All rights reserved. Contents

More information

Expanding Our Horizons. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 9 09/25/2011

Expanding Our Horizons. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 9 09/25/2011 Expanding Our Horizons CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 9 09/25/2011 1 Goals of the Lecture Cover the material in Chapter 8 of our textbook New perspective on objects and encapsulation

More information

Overview. OOP: model, map, reuse, extend. Examples of objects. Introduction to Object Oriented Design

Overview. OOP: model, map, reuse, extend. Examples of objects. Introduction to Object Oriented Design Overview Introduction to Object Oriented Design Understand Classes and Objects. Understand some of the key concepts/features in the Object Oriented paradigm. Benefits of Object Oriented Design paradigm.

More information

Software Engineering I (02161)

Software Engineering I (02161) Software Engineering I (02161) Week 9 Assoc. Prof. Hubert Baumeister DTU Compute Technical University of Denmark Spring 2015 Last Week Software Development Process Version Control Contents Project planning

More information

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107 A abbreviations 17 abstract class 105 abstract data types 105 abstract method 105 abstract types 105 abstraction 92, 105 access level 37 package 114 private 115 protected 115 public 115 accessors 24, 105

More information

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming Polymorphism 1 / 19 Introduction to Object-Oriented Programming Today we ll learn how to combine all the elements of object-oriented programming in the design of a program that handles a company payroll.

More information

Living and Working with Aging Software. Ralph Johnson. University of Illinois at Urbana-Champaign

Living and Working with Aging Software. Ralph Johnson. University of Illinois at Urbana-Champaign Living and Working with Aging Software Ralph Johnson University of Illinois at Urbana-Champaign rjohnson@illinois.edu Old software gets brittle n n Hard to change Hard to understand Software should be

More information

Reverse Engineering and Refactoring Related Concept in Software Engineering

Reverse Engineering and Refactoring Related Concept in Software Engineering Reverse Engineering and Refactoring Related Concept in Software Engineering Ajit kumar and Navin kumar. Research scholars. B. R. Ambedkar Bihar University. Muzaffarpur, Bihar (India). Guide:-Dr.D.L.Das.

More information

G51PGP Programming Paradigms. Lecture OO-4 Aggregation

G51PGP Programming Paradigms. Lecture OO-4 Aggregation G51PGP Programming Paradigms Lecture OO-4 Aggregation 1 The story so far We saw that C code can be converted into Java code Note real object oriented code though Hopefully shows you how much you already

More information

CSC 408F/CSC2105F Lecture Notes

CSC 408F/CSC2105F Lecture Notes CSC 408F/CSC2105F Lecture Notes These lecture notes are provided for the personal use of students taking CSC 408H/CSC 2105H in the Fall term 2004/2005 at the University of Toronto. Copying for purposes

More information

OO Design Principles

OO Design Principles OO Design Principles Software Architecture VO (706.706) Roman Kern Institute for Interactive Systems and Data Science, TU Graz 2018-10-10 Roman Kern (ISDS, TU Graz) OO Design Principles 2018-10-10 1 /

More information

Refactoring. Improving the Design of Existing Code. Second Edition. Martin Fowler with contributions by Kent Beck

Refactoring. Improving the Design of Existing Code. Second Edition. Martin Fowler with contributions by Kent Beck Refactoring Improving the Design of Existing Code Second Edition Martin Fowler with contributions by Kent Beck Contents at a Glance Foreword to the First Edition Preface Chapter 1: Refactoring: A First

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Ray John Pamillo 1/27/2016 1 Nokia Solutions and Networks 2014 Outline: Brief History of OOP Why use OOP? OOP vs Procedural Programming What is OOP? Objects and Classes 4 Pillars

More information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

More information

Course December Adrian Iftene

Course December Adrian Iftene Course 10 12 December 2016 Adrian Iftene adiftene@info.uaic.ro Recapitulation QoS Functional Testing Non-Functional Testing Rotting Design Refactoring 2 QoS = ability to provide different priority to different

More information

COMP 354 TDD and Refactoring

COMP 354 TDD and Refactoring COMP 354 TDD and Refactoring Greg Butler Office: EV 3.219 Computer Science and Software Engineering Concordia University, Montreal, Canada Email: gregb@cs.concordia.ca Winter 2015 Course Web Site: http://users.encs.concordia.ca/

More information

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

Data Abstraction. Hwansoo Han

Data Abstraction. Hwansoo Han Data Abstraction Hwansoo Han Data Abstraction Data abstraction s roots can be found in Simula67 An abstract data type (ADT) is defined In terms of the operations that it supports (i.e., that can be performed

More information

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections Thread Safety Today o Confinement o Threadsafe datatypes Required reading Concurrency Wrapper Collections Optional reading The material in this lecture and the next lecture is inspired by an excellent

More information