Reputation: 75
Always I'm thinking where to put the constants, in interfaces like:
public interface MyInterface {
...
public static final String MY_CONST = "const";
...
}
Or in classes like:
public class MyClass implements MyInterface {
...
public static final String MY_CONST = "const";
...
}
What's the better place to define constants?
Upvotes: 4
Views: 1349
Reputation: 1124
Interface is meant to define contract and not implementation and I see constants as part of implementation because they hold some value for business logic.
So defining constants in a Class make sense. Better explanation and reasoning read this article Define Constants in Interface or Class
Upvotes: 0
Reputation: 109613
Another reason for not using an interface: constant values imported from an interface are embedded in the using class. The import relation disappears. When the interface constant gets a different value, the compiler will not necessarily detect that, and recompile the class.
It is a bit unbelievable, and in fact a fixable bug.
Upvotes: 0
Reputation: 10606
Never use interfaces for defining constants.
For a detailed description, see Robert C. Martin's book Clean Code, or even Josh Bloch's Effective Java. The topic is discussed in details in these works.
The main reason is that they can really confuse someone searching for the value of the constant.
E.g., let's say you have a class A implementing that interface with tons of constants. Then, B also extends that class: you are delegating all the constants to the namespace of the subclass too.
It's a bit like using tons of static imports, which is against readability as well.
Upvotes: 2
Reputation: 200296
The constant interface pattern may be bad practice, but putting a constant in an interface doesn't make it a constant interface. So, if your constant is relevant at the interface level (so relevant to all clients of that interface), go ahead and put the constant into the interface. Nothing wrong with that.
Upvotes: 5
Reputation: 2168
An interface could have many implementations. If the value represented by the constants are common to all implementations, being meaningful in the interface context, is it better to declare them in the interfaces.
Otherwise, if the values are specific to some class implementation, and its descendants, will be better to put them in the class.
There are no right or wrong, but contexts more or less appropriated.
Upvotes: 0