Highly repetitive code is generally a bad thing, and there are design patterns that can help minimize this. However, sometimes it\'s simply inevitable due to the constraints
Java primitive types screw you, especially when it comes to arrays. If you're specifically asking about code involving primitive types, then I would say just try to avoid them. The Object[] method is sufficient if you use the boxed types.
In general, you need lots of unit tests and there really isn't anything else to be done, other than resorting to reflection. Like you said, it's another subject entirely, but don't be too afraid of reflection. Write the DRYest code you can first, then profile it and determine if the reflection performance hit is really bad enough to warrant writing out and maintaining the extra code.
For people that absolutely need performance, boxing and unboxing and generified collections and whatnot are big no-no's.
The same problem happens in performance computing where you need the same complex to work both for float and double (say some of the method shown in Goldberd's "What every computer scientist should know about floating-point numbers" paper).
There's a reason why Trove's TIntIntHashMap
runs circles around Java's HashMap<Integer,Integer>
when working with a similar amount of data.
Now how are Trove collection's source code written?
By using source code instrumentation of course :)
There are several Java libraries for higher performance (much higher than the default Java ones) that use code generators to create the repeated source code.
We all know that "source code instrumentation" is evil and that code generation is crap, but still that's how people who really know what they're doing (i.e. the kind of people that write stuff like Trove) do it :)
For what it is worth we generate source code that contains big warnings like:
/*
* This .java source file has been auto-generated from the template xxxxx
*
* DO NOT MODIFY THIS FILE FOR IT SHALL GET OVERWRITTEN
*
*/
If you absolutely must duplicate code, follow the great examples you've given and group all of that code in one place where it's easy to find and fix when you have to make a change. Document the duplication and, more importantly, the reason for the duplication so that everyone who comes after you is aware of both.