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. 

onsdag 11 december 2013

Design Patterns: Singleton

The most basic of all design patterns is the singleton,

From Wikipedia, "In software engineering, the singleton pattern is a design pattern that restricts the Instantiation of a class to one object."

This means that we can only create ONE instance of a class and that instance should be reused.


public class MySingleton {
   private static MySingleton instance = null;
   protected MySingleton() {
      // Exists only to defeat instantiation.
   }
   public static MySingleton getInstance() {
      if(instance == null) {
         instance = new MySingleton();
      }
      return instance;
   }
}
As can be seen in the example code, this class is a static class containing static methods. When you want to create an instance of the singleton class you call MySingleton.getInstance().
This method check if the static field instance is null, and if it is null then it creates a new instance using the keyword new and return the new instance. In case there already is an instance, we return it directly.

We can't create an instance of MySingleton by using MySingleton myInstance = new MySingleton() since the constructor is defined as protected (only reachable from the class it self, and not by any other class)

Known uses:
- Logging class
- Utility classes


Singleton is considered bad in many cases but it is a fundamental design pattern that everybody should know about.

söndag 8 december 2013

Checkio: House Password

My solution for Checkio assignment House Password:
def checkio(data):
        returnValue = True
        if (len(data) < 10) or (re.search("[A-Z]", data) == None) or (re.search("[a-z]", data) == None) or (re.search("[0-9]", data)) == None:
            returnValue = False
        return returnValue; 

lördag 7 december 2013

Checkio: Non-unique elements

My solution for the second problem (called Non-unique elements) in checkio:
def checkio(data):
    return [x for x in data if data.count(x) >= 2]

Checkio: Extra dashes

My solution for the first problem in Checkio (http://www.checkio.com)
def checkio(line):
    return "-".join([x for x in line.split("-") if x != ""])

difference between weeks

Example, if you have a course that start one week and ends after 10 weeks, and you want to calculate which week you current are in your course.
$currentWeek = strtotime("2013W51");
$startWeek = strtotime("2013W54");
$difference = $currentWeek - $startWeek;

$currentWeek =  date('W', $c);