Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables.class in java

So I know how to reference variables from different classes, but I'm wondering if it's worth me creating a Vars.class to house all my global vars.

This would make it easier for me if I need to change them at a later date however, I'm wondering if this is a bad idea speed wise? Does it take longer to reference a var from a different class?

Thanks

EDIT: When i say 'global variables', I meant 'global constants'. Apologies for the confusion. I want them to be referable from other classes, but they will not be changed on the fly.

Vars.java

package test;

public class Vars
{
    static int variable1 = 16;
    static int variable2 = 32;
}

Start.java

package test;

public class Start
{
    public Start()
    {
        int i = Vars.variable1;
    }
}
like image 394
StewDMill Avatar asked Dec 16 '22 19:12

StewDMill


1 Answers

So I know how to reference variables from different classes, but I'm wondering if it's worth me creating a Vars.class to house all my global vars.

No. It's worth trying to avoid having global variables in the first place. Variables should represent the state of a particular object - so group variables according to sensible boundaries for useful objects, and then make sure that each object knows about whatever other objects it needs to depend on.

There's little point in using an object-oriented language if you're going to throw away object orientation.

Taking the time to work out the appropriate types in your application will no doubt be slower in the very short term than just having global variables... but it'll make your code much easier to maintain and test.

As for performance: you're worrying about that much too early. Access time for variables will almost never be a significant performance impact. Design your code in the simplest way that works. Decide on a performance metric and acceptance criteria. See whether your code already meets those criteria. If it doesn't, work out why it doesn't and perform the cleanest change you can to improve performance (measuring all the time).

Additionally, the variables themselves should almost always be private: storage is an implementation decision; consider how and whether to expose the state through methods.

like image 196
Jon Skeet Avatar answered Dec 30 '22 20:12

Jon Skeet