I've badly failed at an interview recently.
I was ask to write a thread-safe singleton on a dashboard.
I've come up with one of the ugliest code I've ever made (at least, a code that woulnd't anyone to know about)
public class Singleton
{
public static gSingleton;
public void do()
{
}
}
//Calling code
P(Singleton.gSingleton)
Singleton.gSingleton.do();
V(Singleton.gSingleton)
//even forgot that the java keyword is "synchronized"...
=> No encapsulation.
=> Completely missed the fact, that "thread-safe singleton exercise" is not about protecting some "do()" method, but to protect the singleton instantiation.
public class Singleton
{
private static Singleton instanceSingleton;
private static Object lockObject;
public void do()
{
}
//Private constructor !
private static Singleton()
{
}
public static Singleton getInstance()
{
synchronized(lockObject)
{
if (instanceSingleton == null)
{
instanceSingleton = new Singleton();
}
}
return instanceSingleton;
}
}
The truth is that although I don't write a lot of code at work, failing to write to most elementary design pattern is unacceptable. It alway's hard to evaluate someone skills, failling to answer this simple question just killed me right away although the interview was going well so far.
This exercice is meant to see 3 things :
Knowledge of design pattern (singleton)
Knowledge of oriented object programming (encapsulation)
Knowledge of multi-threading (singleton initialization)
You want to put me in trouble in an interview just ask me questions about :
=> .NET framework
=> C++ STL
=> Oracle/PLSQL
=> MS SQL Server
=> SQL Optimization
=> Implementing design pattern !