Global state

Class state (opposed to object state) is persistent to lifetime of JVM.

In Global State multiple executions can produce different results for new A().doSth();

Singleton – design pattern, static object in the global space, each field in a singleton is a holds a global state since it is a global variable. Everything accessible via Singleton instance field has a global variable. They cannot be garbage collected and are kept in JVM for its lifetime.

Singletons are bad for test since tests cannot fully control the state of the Singletons. If Singletons have any dependecies then tests cannot control instantiation process of these fields / dependencies.
BAD: Application has method that internally calls AppSettings.getInstace.doSth(). While testing Application how do you test in doSth() was really called. When AppSettings is a Singleton (design pattern) you cannot test it.
GOOD: Instead of this, design your Appsettings to have public constructor and a non-static doSth() method so that you cannot mock it. Then the Application wiil set AppSetting in the constructor and assign as instance field. Then you can verify if a call to Application method will internally call Appsettings doSth() method.

singleton – a single instance of an object that is intantiated once (only once was the constructor called) and is not attached to global space

you should ensure that objects are instantiated in the correct order and methods are called in the correct order. You can achieve it by explicitly passing the objects referenced to constructor or a method. Then, there is no hidden conversation between the objects and it is harder to make mistakes.

Dependency injection:
– enforces the proper order of initialization at compile time
– helps to define where you want to cut the dependecies boundaries so that you can mock the rest.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s