Locked History Actions

CodeDuplication

Code Duplication

Your Code Stinks: Eliminate or Reduce Code Duplication using Template and Strategy Design Patterns

One of the most common problems I see when I read source code is code duplication. While every developer duplicates some code while developing a solution, not all take the time to refactor it so that it clearly communicates the intent of the code. Why? The reason is because most developers do not understand the value: I'm here to point out that there is huge, huge value.

I recently read an article by Robert Martin, one of my favorite tech authors. In the article Uncle Bob states the following:

  • "If you have been a programmer for more than two or three years, you have probably been significantly slowed down by someone else’s messy code. If you have been a programmer for longer than two or three years, you have probably been slowed down by by your own messy code. Over time, teams that move very fast at the beginning of a project can find themselves moving at a snail’s pace later one. Every change they make to the code breaks two or three other parts of the code. No change is trivial. Every addition or modification to the system requires that the tangles, twists, and knots be “understood” so that more tangles, twists, and knots can be added. Over time the mess becomes so big and so deep and so tall, they can not clean it up."

The degree of the slow-down can be critical to project success. Refactoring such code is an important step that will make your code more easily understood and therefore maintainable. In addition to code standards and conventions, refactoring your code to eliminate code duplication is one of the steps that will take the quality of your code to the next level.

A couple of tools that ought to be in your tool-belt for addressing this problem are the classic Template and Stradegy Design patterns. Depending upon the language you are working with there are some different implementations of these patterns that can be used. Here we will explore these in C# as this is the language I am currently using for most of my projects.

Template Pattern

Example of code duplication - binding a DataSet to a ListView control.

  • Callbacks
  • Callbacks using inheritance
  • Callbacks using delegates
  • Functions as objects
    • Python, Javascript, Ruby

Strategy Pattern