Java static methods pros & cons

后端 未结 4 1241
长情又很酷
长情又很酷 2021-02-08 10:46

I havent used a lot of static methods before, but just recently I tend to use more of them. For example if I want to set a boolean flag in a class, or acess one without the need

4条回答
  •  失恋的感觉
    2021-02-08 11:18

    A problem with using a static variable in this case is that if you create two (or more) instances of MainLoop, writing code that looks like it is shutting down only one of the instances, will actually shut down both of them:

    MainLoop mainLoop1 = new MainLoop();
    MainLoop mainLoop2 = new MainLoop();
    
    new Thread(mainLoop1).start();
    new Thread(mainLoop2).start();
    
    mainLoop1.finished = true; // static variable also shuts down mainLoop2 
    

    This is just one reason (amongst many) for choosing to not use static variables. Even if your program today only creates one MainLoop, it is possible that in the future you may have reason to create many of them: for unit testing, or to implement a cool new feature.

    You may think "if that ever happens, I'll just refactor the program to use member variables instead of static variables." But it's generally more efficient to pay the cost up front, and bake modular design into the program from the start.

    There's no question that statics often make a quick and dirty program easier to write. But for important / complex code that you intend to test, maintain, grow, share, and use for years to come, static variables are generally recommended against.

    As other answers to this question have noted, a static variable is a kind of global variable. And there's lots of information about why (generally) global variables are bad.

提交回复
热议问题