Refactoring 018 - Replace Singleton
Maxi Contieri

Maxi Contieri @mcsee

About: Learn something new every day. - I am a senior software engineer working in industry, teaching and writing on software design, SOLID principles, DDD and TDD.

Location:
Buenos Aires
Joined:
Apr 13, 2020

Refactoring 018 - Replace Singleton

Publish Date: Nov 5 '24
2 1

Breaking Free from the Evil Singleton

TL;DR: Refactor singletons to reduce coupling

Problems Addressed

Related Code Smells

Steps

  1. Identify the singleton
  2. Locate all references to its getInstance() method
  3. Refactor the singleton to a standard class
  4. Inject it as a dependency

Sample Code

Before

public class DatabaseConnection {
    private static DatabaseConnection instance;

    private DatabaseConnection() {}

    public static DatabaseConnection getInstance() {
        if (instance == null) {
            instance = new DatabaseConnection();
        }
        return instance;
    }

    public void connect() { 
    }
}

public class Service {
    public void performTask() {
        DatabaseConnection connection = DatabaseConnection.getInstance();
        connection.connect(); 
    }
}
Enter fullscreen mode Exit fullscreen mode

After

public class DatabaseConnection {  
    // 1. Identify the singleton 
    public void connect() { 
    }
}

public class Service {
    // 2. Locate all references to its getInstance() method.
    private DatabaseConnection connection;

    // 3. Refactor the singleton to a standard class. 
    public Service(DatabaseConnection connection) {
        // 4. Inject it as a dependency.
        this.connection = connection;
    }

    public void performTask() {
        connection.connect(); 
    }
}

DatabaseConnection connection = new DatabaseConnection();
// You can also mock the connection in your tests

Service service = new Service(connection);
service.performTask();
Enter fullscreen mode Exit fullscreen mode

Type

[X] Semi-Automatic

Safety

This refactoring is safe when you update all references to the singleton and handle its dependencies correctly.

Testing each step ensures that no references to the singleton are missed.

Why the code is better?

Refactoring away from a singleton makes the code more modular, testable, and less prone to issues caused by the global state.

Injecting dependencies allows you to easily replace DatabaseConnection with a mock or different implementation in testing and other contexts.

Tags

  • Coupling

Related Refactorings

See also

Credits

Image by PublicDomainPictures from Pixabay


This article is part of the Refactoring Series.

Comments 1 total

  • Muhammad Orhan
    Muhammad OrhanNov 11, 2024

    Secure your connection and unlock exclusive perks—register your Smart SIM today! Fast, easy, and essential for uninterrupted service

Add comment