Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to have code duplication and have it be very simple/readable, or have no duplication (using generics) but be much more complicated?

In general I come across this a lot. Some of my co-workers prefer very simple, easy to read classes even if that means that there is some code duplication, whereas I do everything in my power to avoid code duplication, even if it means making more a complicated architecture. What is the best practice? I work exclusively in Java.

like image 938
darrickc Avatar asked Nov 19 '09 19:11

darrickc


People also ask

Is it okay to duplicate code?

In computer programming, duplicate code is a sequence of source code that occurs more than once, either within a program or across different programs owned or maintained by the same entity. Duplicate code is generally considered undesirable for a number of reasons.

Why is code duplication considered a design anti pattern?

because it goes against Composition over inheritance principle, will force any GameObject who needs to jump to inherit from Character class. This will make the design less flexible.

How do you avoid repetition in code?

To avoid the problem of duplicated bugs, never reuse code by copying and pasting existing code fragments. Instead, put it in a method if it is not already in one, so that you can call it the second time that you need it.


2 Answers

The main reason to avoid code duplication is maintainability. If a segment of code appears in multiple places, when it comes time to update you have to remember to change it everywhere. Forgetting to change one instance can cause big problems, which you may not notice immediately.

like image 117
ThisSuitIsBlackNot Avatar answered Nov 10 '22 00:11

ThisSuitIsBlackNot


While both are good goals, I feel that readability is the absolute first requirement to have a maintainable codebase. I would always prefer simple, readable, and maintainable to a complete elimination of code duplication.

like image 26
Reed Copsey Avatar answered Nov 10 '22 00:11

Reed Copsey