Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it reasonable to use a static instance in Java?

I couldn't really find an answer to this question on google, so here goes.

Is it okay to use a Static object so the rest of the program can reference the object? I don't exactly know how to clarify my question, so I'll just show example code.

public class Client {

    Frame f;
    private static Client mainClient;

    public static void main(String[] args){
        new Client().init();
    }

    private void init(){

        mainClient = this;
        f = new Frame();

    }

    public static Client getClient() {
        return mainClient;
    }

    public Frame getFrame(){
        return f;
    }   
}

So, is it acceptable to use the getClient() method throughout the program to get access to the Frame object, as opposed to sending it as a parameter to (most) of the objects I create? Frame is used throughout the program, and adding it as a parameter just adds one parameter to each constructor.

Thanks

like image 683
Jtvd78 Avatar asked Feb 17 '23 03:02

Jtvd78


1 Answers

Depends on more than one thing...

1) Usage. Do you want to be able to say MyClass.getClient() and get a reference to the Client variable? If you're aiming at a singleton sort of thing - yes. If you're aiming at a very convenient thing - yes if safe, if you just want it visible everywhere - no. If accessing it from wrong place/time causes crashes and bugs - no.

2) People People will use whatever you expose, period. If they see your code fetching Client like that, they will use it when inappropriate as well, so will it cause many bugs? :)

3) Design Do you really need it? Is it cleaner to pass it around like an argument than having absolute access to it at any time?

After gauging those, you decide. This looks like it builds and works fine. But anything that needs this sort of unrestricted access (anytime access mentioned above) to runtime-specifics might not be the best approach; what works for homework might not for enterprise software.

like image 79
Shark Avatar answered Feb 23 '23 11:02

Shark