Duplicating Code And Why I (Try To) Avoid It

Created: January 23, 2015 Tagged As: .net, C#, General, Language Share:

As I have stated in previous articles, I regularly review and often must maintain code written by others. I occasionally see some really brilliant stuff. More often what I witness is a cobbled together mess that is next to impossible to maintain. While improper knowledge of the platform and / or tools being used plays a significant role, design choices are equally if not more to blame.

One of the design choices I find most frustrating is the over-use of copy and paste. Let's say your initial project calls for two entities call Dog and Cat. You write Dog and then simply copy and paste that code and quickly refactor it into Cat. While this works in the initial design, it quickly becomes problematic when changes are needed - and believe me, they will be needed. 

When the client comes to you and asks for 10 new items to be added to both Dog and Cat you now have to make 20 changes to your code. And this gives you the opportunity to introduce 20 bugs!! Not to mention that this code will be harder to read and maintain.

A better design choice from the outset would have been to create a base entity called Animal and the derived both Dog and Cat from that. You could have then added those 10 items to Animal One set of changes. One set of tests. Done.

The moral of the story? Spend a little more time during the initial design phase (and possibly increase your initial project price accordingly) to ensure a proper, solid foundation. Then all changes are less invasive, and in the long run cheaper for the client and better for you, the coder, since you won't be chasing bugs and looking bad.