Refactoring-Improving the Design of Existing Code——学习札记(2)
Chapter 7 Moving Features Between Objects
(1)Move Method
A method is, orwill be, using or used by more features of another class than the class onwhich it is defined. Create a new method with a similar body in the class ituses most. Either turn the old method into a simple delegation, or remove italtogether.
(2)Move Field
A field is, orwill be, bused by another class more than the class on which it is defined.Create a new field in the target class, and change all its users.
(3)Extract Class
You have oneclass doing work that should be done by two. Create a new class and move therelevant fields and methods from the old class into the new class.
(4)Inline Class
A class isn’tdoing very much. Move all its features into another class and delete it.
(5)Hide Delegate
A client iscalling a delegate class of an object. Create methods on the server to hide thedelegate.
(6)Remove Middle Man
A class is doing too much simpledelegation. Get the client to call the delegate directly.
(7)IntroduceForeign Method
A server class you are using needs an additional method, but you can’tmodify the class. Create a method in the client class with an instance of theserver class as its first argument.
Date newStart = new Date(previousEnd.getYear(), previousEnd.getMonth(), previousEnd.getDate()+1); |
重构后:
Date newstart = nextDay(previousEnd);
private static Date nextDay(Date arg) { return new Date (arg.getYear(),arg.getMonth(),arg.getDate()+1); } |
(8)IntroduceLocal Extension
A server class you are using needs several additional methods, butyou can’t modify the class. Create a new class that contains these extramethods. Make this extension class a subclass or a wrapper of the original.