Reputation: 217
Recently, I've noticed a ton of people doing things like:
class One {
public static final String anything = "Hi!";
public static String getAnything(){
return anything;
}
}
class Two { // This is not an inner class
System.out.println(One.getAnything());
}
Vs
class One {
public static final String anything = "Hi!";
}
class Two {
System.out.println(One.anything);
}
Is there any more benefit to each one? And which one do you guys think is better?
Upvotes: 0
Views: 94
Reputation: 24383
If anything
is static final
(as in your example), then there is no difference.
However, using the getAnything()
method allows the functionality to be changed without having to refactor code. For instance, logging could be added inside the getAnything()
implementation.
If you implement a getAnything()
method, it would be conventional to change the visibility of anything
from public
to private
.
Upvotes: 3
Reputation: 122008
IMHO,There is no difference.Both are serving for the same purpose.
But a small difference will be
public static String getAnything(){
//Hey someone taking value of anything.Do something here.
return anything;
}
Which is not possible to track if you use
System.out.println(One.anything);
If there is need not to do anything,I prefer to write One.anything
which is clean to read.
Upvotes: 0