DEV Community

Discussion on: Java interview prep: 15 Java interview questions

Collapse
 
elmuerte profile image
Michiel Hendriks

Of course global state appears in the real world. Just like memory leaks, concurrent modifications, and a whole lot of other bad things.

Configuration files and DB connection parameters do not have to be global state. You should pass them along as context or local state. Within a context (like Spring's ApplicationContext) you can have a single instance of an object. It is much like a singleton, except that it is possible to have a completely different instance of that object in a different context. Via the context you can get the proper instance of that object.

Depending on a global state is also problematic with unit testing.

It is simply best to avoid using singletons. However it is not always possible without creating a bigger mess. The prime example would be logging.

Thread Thread
 
aminmansuri profile image
hidden_dude

I see. I guess that's the heart and soul of the IOC / Hollywood principle. Rather than have your methods calling global classes for something, they should have those set for them so its easier to test.