3.6. A Prefactoring Attitude

 <  Day Day Up  >  

As you write your code, be conscious of the way you are writing it. Use a "prefactoring" editor attitude. It is OK to cut a block of code and paste it elsewhere. That usually means you're moving it to a better position: into a separate method, as detailed in Martin Fowler's Extract Method. If you find yourself copying and pasting a block of code, stop and analyze what you are copying. Should you place that code into a method? If so, why not place it there now, to prevent code duplication before it occurs?

Are you using the code you are copying as a template? Then why not create a template? A source code template is good for creating a common pattern in the layout of your classes. For example, if you decide that all classes should have to_string( ) and from_string( ) methods, set up a source code base that includes those methods. Whenever a developer creates a new class, she can copy that template into the new class source. This is "the exception to the rule" of copying and pasting more than a single line. In this case, there is a justifiable reason for the copy and paste: interface consistency. You can create a "wizard" to perform automatic text replacements . If your integrated development environment (IDE) supports an "implement interface" command, this template should be an interface. The act of implementing it creates the skeleton code for the methods of the implementing class.

ADAPT A PREFACTORING ATTITUDE

Eliminate duplication before it occurs.


When you find yourself writing a comment for a section of code, ask yourself why you are commenting it. Are you describing how you are implementing a particular algorithm within the method? If so, the section of code should probably be its own method. For example:

 int [] array;     int odd_number;     // Find the first odd number in the array     for (int m=1; m < array.length; m++)         {         if (array[m] % 2  == 1)             {             odd_number = array[m];             break;             }         } 

This block could be turned into a method, such as the following:

 int find_first_odd_number_in_array(int [] array); 

 <  Day Day Up  >  


Prefactoring
Prefactoring: Extreme Abstraction, Extreme Separation, Extreme Readability
ISBN: 0596008740
EAN: 2147483647
Year: 2005
Pages: 175
Authors: Ken Pugh

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net