0

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 !

  • 'Not in a static Constants class, because I'm trying to avoid those'. Can you please provide information for this? – npinti Jun 9 '14 at 6:03
  • I usually try to avoid creating "Constants" classes that contains exclusively static constants. Like Constants.TIMEOUT_DURATION and Constants.BLUETOOTH_UUID Because that's creating a dependency to lots of classes. If I put it in the interface, there's no new dependencies, but since that's not part of my API, it feels bad to have it here. – Taiko Jun 9 '14 at 6:07
  • I see. Personally I tend to opt for the constant class, since that provides means of having all the constants defined in one place. The other option is to go with what @Christian Bongiorno is recommending. – npinti Jun 9 '14 at 6:23
1

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.

0

Why not in a static Constant class? I have seen popular framework like SWT putting lot of constants in a constant class if the usage is widespread. And even in the case where the usage is not widespread, how is it a bad idea. A constant is not much of an implementation detail.

Please correct me if I am wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.