Java - Global variables vs Global methods

1.6k views Asked by At

I was looking into a project whit 5000+ classes, then I see this in each class:

private static int foo = 1;

private static void setfoo(int value)
{
     foo = value;
}

private static int getfoo()
{
     return foo;
}

so, I think why dont use a global variable and set it if anyway is static.

There is a resource use difference between global methods and variables?

Thanks you.

3

There are 3 answers

1
MrSmith42 On BEST ANSWER

Getters and Setters are useful, if you e.g want to add validation in the future (or add logging, or make access statistics or ...)

4
cHao On

If the getter/setter exist, always use them. getFoo and setFoo effectively define a property named "Foo", which is conceptually different from your variable foo. foo is just the variable holding the current value of that property, and could be considered as belonging to the property.

Keep in mind, though, a property doesn't have to just get/set its backing variable. It could also validate the value you pass in before setting it. It could synchronize access to the variable. And/or in the future, a setter might alter the characteristics of some other thing, and the getter could return the current state of that other thing, without even needing the backing variable. By setting the variable directly, you create compatibility issues in the case where the property is/would be changed to do any of that in the future.

If, however, you know that setFoo does (and, in the near future, will still do) nothing other than set a variable named foo, then it'd actually be better to not have a getter/setter. They're not any cleaner, or more readable, and they're certainly not more efficient; a = 3; doStuffWith(a); beats setA(3); doStuffWith(getA()); on all counts. And their absence rids you of the conceptual baggage of a property where you only need a variable. Only add the getter/setter when you need (or definitely will need very soon) the special behavior a property can provide. But once you've added them, use them everywhere.

0
KDjava On

Both the field and getter and setter are private and static.. This means their intended purpose is to be used within the class only . So if you create it at some all class accessible place(globally accessible) , another public class then also you will have to keep track of the field as in every class it has to be initialized to some value before being used (in ur case its 1 i feel). Also you will have to make this code mutually exclusive to keep it correct all the time( would really make it slow if called 5000 times).. Take your call.. its all upto you..