javastatic

Static vs Instance for Global state variable


I have a global boolean variable which I use to disable all trading in my financial trading system. I disable trading if there is any uncaught exception or a variety of other conditions (e.g. no money in account).

Should this variable be static or an instance variable? If its an instance I will need to add it to constructors of loads of classes...Not sure if its worth the hassle.

Thxs.


Solution

  • Static Pros: No need to pass references to instance to every class which will be using this

    Static Cons: May lead to difficult in testing - I think it should be fairly easy to test a static variable if you set the state of the variable before and after the test (assuming the tests are not running concurrently).

    Conclusion: I think the choice here depends on what your view of testing static variables is...For this simple case of one variable managing the state I really cant see the problem with using static. On the otherhand...its not really that hard to pass an instance to the constructors of the dependent classes so you dont really have any downside when using the instance approach.