Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top