Java Best Practices – Interface Subclasses and Constants

interfacesjava

In the case where a couple of classes implements an interface, and those classes have a couple of constants in common (but no functions), were should I put this constant ?

I've had this problem a couple of times.

I have this interface : DataFromSensors that I use to hide the implementations of several sub classes like DataFromHeartRateMonitor DataFromGps etc…

For some reason, those classes uses the same constants. And there's nowere else in the code were it is used.

My question is, were should I put those constants ?

Not in the interface, because it has nothing to do with my API

Not in a static Constants class, because I'm trying to avoid those

Not in a common abstract class, that would stand between the interface and the subclasses, because I have no functions in common, only a couple of constants (TIMEOUT_DURATION, UUID, those kind of things)

I've read best practice for constants and interface to define constants but they don't really answer my question.

Thanks !

Best Answer

The other thing you can do is specify it in a config resource that you include with a jar. Constants are kinda funny: You think they never need to change until they do and then you have to recompile to code to change your TIMEOUT_VALUE.

If you put it in the jar with the rest of the resources then it is, for all intents and purposes, constant. However, it's not code and, in the off chance you have a problem, you can modify it in the field.

Just an idea. Putting statics in the interface is only a problem if it's the ONLY thing that interface does. Somethings in programming just are ugly and you have to make some tradeoffs.