Search code examples
functionduplicatescoding-stylecode-duplicationcode-cleanup

Do we need to avoid duplicate at any cost?


In our application framework ,whenever a code duplicate starts happen (even in slightest degree) people immediately wanted it to be removed and added as separate function. Though it is good ,when it is being done at the early stage of development soon that function need to be changed in an unexpected way. Then they add if condition and other condition to make that function stay.

Is duplicate really evil? I feel we can wait for triplication (duplicate in three places ) to occur before making it as a function. But i am being seen as alien if i suggest this. Do we need to avoid duplicate at any cost ?


Solution

  • There is a quote from Donald Knuth that pin points your question:

    The real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature optimization is the root of all evil (or at least most of it) in programming.

    I think that duplication is needed so we are able to understand what are the critical points that need to be DRYed.

    Duplicated code is something that should be avoided but there are some (less frequent) contexts where abstractions may lead you to poor code, for example when writing test specs some degree of repetition may keep your code easier to maintain.

    I guess you should always ask what is the gain of another abstraction and if there is no quick win you may leave some duplicated code and add TODO comment, this will make you code faster, deliver earlier and DRY only what is most valued.

    A similar approach is described by Three Strikes And You Refactor:

    1. The first time you do something, you just do it.
    2. The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyway. (Or if you're like me, you don't wince just yet -- because your DuplicationRefactoringThreshold is 3 or 4.)
    3. The third time you do something similar, you refactor.