Sobes.tech
Junior — Middle

What is the downside of implementing Singleton through manual code and why is it considered bad practice?

sobes.tech AI

Answer from AI

Implementing Singleton through manual code is often considered a bad practice for several reasons:

  1. Thread safety issues. If proper synchronization mechanisms (such as synchronized or volatile) are not used, multiple instances may be created when accessed concurrently from multiple threads.

  2. Testing difficulty. Singleton makes unit testing harder because its state is global and can persist between tests, causing side effects.

  3. Tight coupling. Using Singleton leads to strong coupling in the code, reducing flexibility and complicating maintenance.

  4. Class loading issues. Manual implementation can cause initialization problems, especially in complex systems with multiple class loaders.

  5. Better alternatives. In Java, there are more reliable ways to create Singletons, such as using enum or static nested classes, which provide thread safety and simplicity.

Example of a poor Singleton implementation:

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton(); // not thread-safe
        }
        return instance;
    }
}

In this example, calling getInstance() concurrently from different threads can create multiple instances, violating the Singleton principle.

What is the downside of implementing Singleton… - sobes.tech