views:

96

answers:

3

I'm revisiting data structures and algorithms to refresh my knowledge and from time to time I stumble across this problem:

Often, several data structures do need to swap some elements on the underlying array. So I implement the swap() method in ADT1, ADT2 as a private non-static method. The good thing is, being a private method I don't need to check on the parameters, the bad thing is redundancy. But if I put the swap() method in a helper class as a public static method, I need to check the indices every time for validity, making the swap call very unefficient when many swaps are done.

So what should I do? Neglect the performance degragation, or write small but redundant code?

+2  A: 

If you don't need to make the checks in the private method, don't make them in the static one. This will result in a RuntimeException for invalid calls, but since all your calls are supposed to be valid, it will be as though you've used a private method.

Bozho
+5  A: 

Better design should always trump small inefficiencies. Only address performance problem if it actually is proven to be one.

Besides, what kind of checking are you doing anyway? Aren't naturally thrown ArrayIndexOutOfBoundsException and/or NullPointerException good enough?


It's worth nothing that while there's public static Collections.swap(List<?>,int,int), java.util.Arrays makes its overloads (for int[], long[], byte[], etc) all private static.

I'm not sure if Josh Bloch ever explicitly addressed why he did that, but one might guess that it has something to do with Item 25 on his book Effective Java 2nd Edition: Prefer lists to arrays. Yes, there will be "performance degradation" in using List, but it's negligible, and the many advantages more than make up for it.

polygenelubricants
The private swap methods of the Arrays class also made me wonder. Sure, efficience is not that important for some homework assignment but if you were to design and publish a data structure, it could make a difference.
Helper Method
+1  A: 

It's always better for your code to be less efficient than to be duplicated (some constant calls are not considerable). At least that is what is taught at my university.

Code duplication produces bugs. So you prefer your program to work correctly rather than to work a little faster.

If you want to prevent constraints checking: what comes to my mind is that you can either accept naturally thrown exceptions as polygenelubricants suggested or create an abstract super class to all your data structures based on arrays. That abstract class would have protected method swap that will not check parameters. It's not perfect, but I guess that a protected method that does not check parameters is better than a public method that does not do it.

drasto