Search code examples
javaconstants

What are your thoughts on method scoped constants?


For example:

public void doSomething() {

    final double MIN_INTEREST = 0.0;

    // ...  
}

Personally, I would rather see these substitution constants declared statically at the class level. I suppose I'm looking for an "industry viewpoint" on the matter.


Solution

  • My starting position is that every variable or constant should be declared/initialized as close to its first use as possible/practical (i.e. don't break a logical block of code in half, just to declare a few lines closer), and scoped as tightly as possible. -- Unless you can give me a damn good reason why it should be different.

    For example, a method scoped final won't be visible in the public API. Sometimes this bit of information could be quite useful to the users of your class, and should be moved up.

    In the example you gave in the question, I would say that MIN_INTEREST is probably one of those pieces of information that a user would like to get their hands on, and it should be scoped to the class, not the method. (Although, there is no context to the example code, and my assumption could be completely wrong.)