Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do you keep Constants used throughout your application?

Is interface an acceptable place to store my

public static final Foo bar 

Do you extrapolate them to be read from outside of the program? Do you make up a super class for it?

How do you do it, when situation presents itself?

like image 909
James Raitsev Avatar asked Jun 02 '11 21:06

James Raitsev


People also ask

Where do you put constants files?

For runtime constants: use static const in source file for local constants, or for global constants non-static const in source and extern const of it in header.

Where should I store constants Java?

Even if a constant is used throughout the code but always in relation to one class, it should clearly be part of that class (e.g. BorderLayout. CENTER).

Where do constants go in clean architecture?

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.

Where should global constants be placed in a program?

Really global (application-level) constants should be in the application's namespace (provided your application is inside it's own namespace, as it should be). For module-level constants, the module's own namespace is the natural place.


1 Answers

I'd put each constant into the class or interface it's most closely related to (e.g. because it will be use by its methods).

A very seductive but ultimately very foolish idea is to have one "constants class" (or interface) that contains all constants used in the application. This looks "neat" at first glance, but is not good for maintainability because you want to group things by the functionality they implement, not by technical details like being constants (would you put all interfaces into a dedicated package? All abstract classes?).

The idea is also foolish because any change to that class/interface then (because of constant inlining) requires all classes that use any of the constants to be rebuilt - i.e. pretty much the entire app. So the bigger the app gets, the more frequently you need such a full rebuild, and the longer it takes. I worked on such a project, where this issue led to a 15 minute pause about every other day for every developer...

like image 161
Michael Borgwardt Avatar answered Sep 20 '22 05:09

Michael Borgwardt