DEV Community

Discussion on: Java interview prep: 15 Java interview questions

Collapse
 
aminmansuri profile image
hidden_dude

Well, global state appears in the real world. Like configurations files, db connection parameters, etc..
One advantage of using factory methods + singletons is that if for whatever reason you don't want it to be a singleton any more, there's no obligation that it continue to be a singleton.

I'm not sure that making sure its a single instance in the VM is the most overriding principle. I haven't had much need for that guarantee. More important is the abstraction of returning an object that represents some configuration. Which over time could become several objects (for example when you make your app multi-tenant)

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.