Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it not recommended to store constants in a separate class?

Tags:

It's been told me (and I have seen this statement in a few other places) that it's not recommended to store your constants in a separate class in Java, in order to use them in the other classes. But I haven't seen anywhere WHY is it so. What is the reason I should not store them in their own interface/class?


I came from C to Java and in C i would just make a .h file where i defined constants with #define

like image 727
Mihai Bujanca Avatar asked Feb 24 '13 20:02

Mihai Bujanca


People also ask

Should constants be in separate file?

Even if constants are related, they should not be put into a single file. The wrapper classes in Java is a good example of related constants being defined in their own class files rather than in a WrapperConstants file.

Why constants should not be defined in interfaces?

That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them.

Should constants be in interface or class?

You should do it in a class. An Interface is a description of available methods, properties etc that class users can access - by implementing an interface, you guarantee that the members declared in the interface are available to the user.

Where should you declare constants?

You declare a constant within a procedure or in the declarations section of a module, class, or structure.


1 Answers

Constants in a dedicated file are frowned upon for stylistic reasons. Having a class dedicated to constants can encourage developers to add increasing numbers of unrelated (undocumented?) constants to a file that slowly bloats out of control.

By contrast, having constants associated with the classes they are related to is a more scalable and readable design.

like image 95
Duncan Jones Avatar answered Sep 22 '22 09:09

Duncan Jones