Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are your thoughts on method scoped constants?

Tags:

java

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.

like image 558
Liggy Avatar asked Oct 28 '08 17:10

Liggy


People also ask

What are the benefits of using constants in Java?

A constant can make our program more easily read and understood by others. In addition, a constant is cached by the JVM as well as our application, so using a constant can improve performance. To define a variable as a constant, we just need to add the keyword “final” in front of the variable declaration.

Which is the best way to describe the constant literals in a class?

The public|private static final TYPE NAME = VALUE; pattern is a good way of declaring a constant.

What is the scope of a constant in Java?

A constant is a variable whose value cannot change once it has been assigned. Java doesn't have built-in support for constants, but the variable modifiers static and final can be used to effectively create one. Constants can make your program more easily read and understood by others.

How do you manage a constant in Java?

To make any variable a constant, we must use 'static' and 'final' modifiers in the following manner: Syntax to assign a constant value in java: static final datatype identifier_name = constant; The static modifier causes the variable to be available without an instance of it's defining class being loaded.


2 Answers

I would think that you should only put them at the class level if they are used by multiple methods. If it is only used in that method then that looks fine to me.

like image 143
chills42 Avatar answered Sep 19 '22 14:09

chills42


My starting position is that every variable or constant should be declared/initialized as close to it's 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 quit 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.)

like image 39
Chris Cudmore Avatar answered Sep 21 '22 14:09

Chris Cudmore