The best way to implement a Singleton

OWH. MY. GOD.

The more I study about OCPJP, the more I make clear how stranger I am to this language.

Guys, herewith I share with you ta code-snippet:

public enum Employee {
    INSTANCE;
}

Owh, sorry, April’s fool in September, that wasn’t a code snippet, it was an implementation of the Singleton pattern.

Below you can read Joshua’s Block view about this, from his Effective Java book:

This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

Advertisements

Passing null to overloaded methods

Assume we have an overloaded method that looks like this:

public String retrieveValue(String text) {
    return text;
}

public int retrieveValue(int number) {
    return number;
}

Pretty nice overloading, eh?! What could go wrong, for retrieveValue(null) method? In the above code, nothing, because the method with the String signature will be invoked, as the one with the int signature is just of type primitive, so, it’s almost obvious for the compiler.

However, can you imagine what would happen, if the second method accepted an argument of Integer?

public String retrieveValue(String text) {
    return text;
}

public int retrieveValue(Integer number) {
    return number;
}

Integer is the wrapper class of int and what generally stands for the wrapper classes of primitives is that they can also accept null values. So, calling retrieveValue(null) in this case will just confuse the compiler, ‘cuz it’s just ambiguous for him which method to pick up, since both of them can accept a null value argument.

Therefore, there will be a compilation error of:

Ambiguous method call. Both 
retrieveValue (String) in TestClass and
retrieveValue (Integer) in TestClass match

Cheers!