Sunday, October 7, 2007

Avoiding clipboard inheritance

Clipboard inheritance is the practice of copying code from one location (class or method) to another in order to transfer functionality. It is highly likely to introduce bugs into your application for several reasons:

  • Any bugs in the copied code will be transfered to the new location.
  • Any fixes will need to be made everywhere the code was copied; it's easy to miss one.
  • Code specific to the old location can be missed when inserting and modifying the copied code.

Instead follow the Once Only Rule: Any significant code should be in one and only one place in your code.

This will mean refactoring the code to extract the functionality. If the code is repeated within a class then it should be extracted to a new method that can be used throughout the class. If the functionality is used by multiple classes then the functionality should be extracted to a new class which can be used by the other classes (composition).

0 comments: