onsdag 9 april 2014

Why the singleton pattern is bad and shouldn't be used



Singleton has its uses, for example logging can be considered to be an "OK" singleton class, since we don't want to create a new instance everytime we decide to log something in our application.

But many developer consider Singleton to be bad, a very bad design pattern and it shouldn't be used.
But when asked, many developer can't explain WHY it shouldn't be used so I decided to scan the internet after reasons why we as developers shouldn't use the singleton pattern.

Reason 1:

Singleton is the most over-used design pattern that exist.

Reason 2:

Singleton introduce a global state in the code, allowing any class to access it at anytime from anywhere.
This, by it self, should be the only reason why we shouldn't use Singleton pattern at all if we can avoid it.
This is bad because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell.

Reason 3:

They violate the single responsibility principle: by virtue of the fact that they control their own creation and lifecycle.

Wikipedia about single responsibility principle: "In object-oriented programming, the single responsibility principle states that every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class."



Reason 4:

They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.

Reason 5:

They carry state around for the lifetime of the application. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other.


This is a just a few reason why you shouldn't use a singleton, however before throwing all your singleton out from your code try to be pragmatic. 
By trying to avoid Singleton as much as possible I think we in many cases can come up with better ideas about how to solve a certain problem. But if that is not possible, a singleton is of course OK to use in my opinion.

Sources:
https://code.google.com/p/google-singleton-detector/wiki/WhySingletonsAreControversial

tisdag 21 januari 2014

Missing required permissions manifest attribute in main jar

When I updated java to the latest security fix, I got this error message:
"Missing required permissions manifest attribute in main jar"

The solution in my case was to add the URL I tried to access to Java Exception Site list.

On MAC open system preferences, click on Java and a new window opens up. Click the security tab and press Edit Site list.

Restart the web browser just in case and try to access the site again.