Download Object Oriented Programming and more Slides Object Oriented Programming in PDF only on Docsity! 1 Refactoring » What is Refactoring? Refactoring is the process of changing a software system so that the external behavior is not altered, but the internal structure is improved. Refactoring (http://www.refactoring.com/) is a “behavior-preserving transformation.” Small changes per transformation less likely to go wrong System works after each change 2 Refactoring » Why Refactoring? Methods might no longer do (only) what their name suggests. Functionality that should be in two different classes might be in the same class. Functionality that should be in one class might be duplicated in two or more classes. Improve the design of existing code. Gain a better understanding of the code. 5 Refactoring » Example Better: Changing the name of the method (for example, calculateCustomerCharge). What else do we need to do to solve the problem? We also need to change the name at all call sites. We need to update the documentation. If this method overrides a method in another class, the other name may need to be changed too. Ditto if this method implements an interface. This is known as the Rename Method refactoring. 6 Refactoring » Example Let’s refactor our getRoomCharge() method. public double calculateCustomerCharge() { double roomCharge = getRoomCharge(); double incidentals = getIncidentals(); double tax = getTax(roomCharge, incidentals); return roomCharge + incidentals + tax; } What have we done? We defined additional methods to compute incidentals, tax, etc. In order to do this, we added local variables for the quantities that are being calculated in the new methods. Some pre-existing local variables ended up being parameters to the new method. The returned value is different from what was returned in the pre- existing method. 7 Refactoring » Common Refactorings Rename Methods, Fields, Packages, Projects, Parameters, or Local Variables Encapsulate Field (generate getter and setter) Pull up a Field or Method (into superclass) Push down a Field or Method (into subclass) Extract Method, Local Variable, or Constant from an Expression Change Method Signature