views:

65

answers:

2

I have a class that already has a 'natural' order, and wish to define a different Comparator that can be used similar to String.CASE_INSENSITIVE_ORDER - i.e., define it as an instantiated static field to be referred to when needed.

With an interface Foo which is the actual comparison type (it will be Comparator<Foo>), I'm in favor of putting it there rather than FooImpl (only one implementation in this specific case, if that makes a difference). It is implemented using an inner class similar to the String one, except of course that class must be public since Foo is an interface.

Wondering if it is better to put it in FooImpl instead of Foo, and if so why? Also I don't care about the public visibility of the implementing class, but should it be a standalone seperate package visible entity instead?

+3  A: 

If it's specific to the interface, put in interface. If it's specific to the implementation, put in implementation. That makes also the most sense. The current amount of implementations don't matter. You can anyway always provide an implementation its own implementation-specific comparator.

BalusC
I'm using that reasoning and putting it in Foo, since there is nothing specific to FooImpl for the comparison. Just wanted to know any caveats to be aware of, the only difference I can see is the class being visible which as stated is not an issue.
Alok
+1  A: 

Is the Comparator intended to be used outside of FooImpl? If so, you can just put it in the interface as you would an enum. I'd not put it in FooImpl if any of the code using the new comparator are using the Foo interface only.

They shouldn't need to know about FooImpl just to use the Comparator.

Fly