The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

Is duplicate code always bad?

Hello, over the last days i thought about possible advantages from having duplicate code.

Lets assume we have two functions that do the same: F1 and F2

Lets assume that later in time, we want to implement F3, which is very similar to F1 (and F2). If the programmer had deleted F2, he will have to write F3 from scratch, but if he had kept F2, he will have to alter fewer lines of code to implement F3, since some of the code needed was already in F2. Hence it would have been better if the programmer had not deleted F2.

Re: Is duplicate code always bad?

What? Whether copying and pasting are available or not has nothing to do with repeating code.

Duplicate code is always bad, or at least a sign of a bad design. Why are you trying to argue for it?

If you want to continue this discussion, I highly suggest coming up with a concrete example with actual code instead of imagining scenarios. What if your space bar falls off? What if your electricity goes out?

Re: Is duplicate code always bad?

If two methods are exact copies of each other then there's no reason to keep both. At the very least for legacy reasons one method could simply call the other one. This will make maintenance much easier.

However, just because two methods appear to take the same inputs and produce the same outputs doesn't necessarily mean they must arrive at the solution the same way. This is a good way to test out new solutions which may work better (i.e. looks cleaner, runs faster, or uses less memory). It's also entirely possible that both methods have their useful inputs. For example:

Consider the naive primality checker. It's quite inefficient, but for small numbers it's extremely fast. However, for larger numbers it's much quicker to check using a probabilistic primality checker. These methods have a larger overhead so it's not really great to use them with small numbers, but for larger numbers this overhead is significantly smaller than time spent performing useful computation. Different data structures are also a good example (e.g. linked lists vs. array lists).