3.6. A Prefactoring Attitude

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. ...

Get Prefactoring now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.