I generally declare every constant in my applications as a private static final
variable, for a number of reasons.
- Consistency. It's clear to myself and others what are the default core constant definitions are in my application. I can keep them all grouped together, and it's very easy to navigate over to them if they need to be modified. Because they're
static
, these changes ripple down through every call. This safegaurds you from making accidentally multiple definitions of the same constant.
- Performance. If I have a constant that's never changed, there's no point in constantly allocating memory for it during a method call. It's allocated once when a reference to the class is made, and then you're done with it. There that memory remains references until all references to the class are done with.
- Good practice. There's a convention in programming where dependencies of should be as highly decoupled as possible. When you declare a function or variable as
static
, you enforce that it must be interacted with in a static way, i.e. independently of a runtime instance. Without this dependency of a class encapsulating member variables at runtime, you can more precisely control interaction with that class, because it ensures you define precise rules on how a class can be interacted with. You find that the more constants and methods you can declare as static
, the more flexible your software becomes because there's little confusion over how certain values and behaviours are supposed to be manipulated.
- Exposure. Some functions or constants you define may be useful to other parts of your application. This means you can take advantage of functionality without the requirement for using a runtime instance. For example, the quadratic formula is the same everywhere, so why should it belong to a single instance at all? The same goes for constants, like the speed of light.
Personally, I always declare all functionality of my application as private static
. If it makes sense for a class to use that functionality as part of it's operation, then the programmer can wrap the method call in another method and provide the appropriate member variable data. If another part of your application needs to use that static function, all you need to do is increase the visibility of the function.