This is the simplest and often the easiest to find. This is when you have sections of code that are identical or nearly so. This is often a result of copy & paste programming. Several techniques can be used to eliminate it, including: extracting methods and reusing them, making a method into a template method, pulling it up into a superclass, and providing the variations in subclasses, and other basic refactorings.
In my understanding, the Template pattern provides support for managing variation in behaviour. How it helps to counter code duplication is something I am not familiar with. Anyone care to explain ? Thanks.
Basically you extract the duplicate code in the subclasses to a parent class, and only make the code that is unique to a subclass in the subclass.
So for instance, in the HF Design Patterns book they use an example of making coffee and tea. The process of making hot water and pouring into a cup are identical to both coffee and tea, so the parent class will have that code. The subclasses only has code that is specific to either coffee or tea. Like particular condiments being added to the drinks. You normally only use Cream in coffee and not in tea.
With other words, Template Method helps reduce duplication if the duplicated code differs in some small details. The similarities are extracted into the abstract base class, the concrete subclasses only contain the differences in behaviour.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop