Coding Style – Understanding Illusory Code Duplication

coding-style

The usual instinct is to remove any code duplication that you see in the code. However, I found myself in a situation where the duplication is illusory.

To describe the situation in more details: I am developing a web application, and most views are basically the same – they display a list of items which the user can scroll and choose from, a second list that contains selected items, and a "Save" button to save the new list.

It seemed to me that the problem is easy. However, each and every view has its own quirks – sometimes you need to recalculate something, sometimes you must store some additional data etc. These, I solved by inserting callback hooks in the main logic code.

There are so many minute differences between the views that it is becoming less and less maintainable, because I need to provide callbacks for basically all functionality, and the main logic starts to look like a huge sequence of callback invocations. In the end I am not saving any time or code, because every view has its own code that is executed – all in callbacks.

The problems are:

  • the differences are so minute that the code looks almost exactly alike in all views,
  • there are so many differences that when you look at the details, to code is not a bit alike

How should I handle this situation?
Is having core logic composed entirely of callback calls a good solution?
Or should I rather duplicate the code and drop the complexity of callback-based code?

Best Answer

Ultimately you have to make a judgment call about whether to combine similar code to eliminate duplication.

There seems to be an unfortunate tendency to take principles like "Don't repeat yourself" as rules that must be followed by rote at all times. In fact, these are not universal rules but guidelines that should help you think about and develop good design.

As everything in life, you must consider the benefits versus the costs. How much duplicated code will be removed? How many times is the code repeated? How much effort will it be to write a more generic design? How much are you likely to develop the code in the future? And so on.

Without knowing your specific code, this is unclear. Perhaps there is a more elegant way to remove duplication (such as that suggested by LindaJeanne). Or, perhaps there simply isn't enough true repetition to warrant abstraction.

Insufficient attention to design is a pitfall, but also beware over-design.

Related Topic