Java Reference
In-Depth Information
Refactoring Scenarios
Let us see in what scenarios a refactoring needs to be done.
Rename : Some classes and class members may need to be renamed given their changed
usage and old names no longer valid. Good naming of classes and class members is
always welcome because it leads to clarity. For example you may have a class named is-
sue_chequebook. Now the same class is going to be used for issuing debit cards as well. It
will be good if you change this class name to something like issue_chequebook_debitcard.
When you rename a class or any class member then you will have to change the name every-
where it is used in the entire package or the entire application.
Move class : in some cases a class may need to be moved to another package as this class
will be used by classes belonging to this package. In this case you will have to change the
package name of the class wherever it is referenced. You will also need to update the source
control (configuration management) system also.
Extract Method: When a long method needs to be broken up to enhance readability and
maintainability then you have to do refactoring. A section of code with a single logical task
(e.g. find a record by id) is replaced with an invocation to a new method. This new method
is given suitable parameters, return type and exceptions. By giving the method a clear and
descriptive name, the original method becomes simpler to understand. Extracting the meth-
od also allows the method to be reused in other places, otherwise not possible when it was
just part of a larger method. If the extracted section is well chosen, this method may be a nat-
ural place to change the behavior of the class through subclassing (creating a similar class),
rather than a copy and paste of the existing method which was the case before you made the
changes.
Extract Superclass: In some cases an existing class provides functionality that needs to be
modified in some way. A super class (a class from which the existing class will inherit struc-
ture) can be introduced as the parent of the current class, and then common behavior is
pulled up into this new parent. Clients of the existing class are changed to reference the new
parent class, allowing alternative implementations (polymorphism). Any methods which are
common to the concrete classes are pulled up with definitions, while those that will vary in
subclasses may not need to be implemented. As well as aiding in efficient code re-use, it
also allows new subclasses to be created and used without changing the client classes.
Search WWH ::




Custom Search