AlgoViz

Singleton

medium 60 min

One object and one way to reach it.

Watch lesson4:52

Refactor

Keep the one object, lose the global door.

The point: the number of objects is decided in one place, main. The classes only say what they need.

The smell

A test that depends on another test

Python
class Flags:    _instance = None    @classmethod    def get(cls):        if cls._instance is None:            cls._instance = cls()        return cls._instance    def __init__(self):        self.on = set()def page():    return "new" if "new-checkout" in Flags.get().on else "classic"def test_new():    Flags.get().on.add("new-checkout")    assert page() == "new"def test_classic():    assert page() == "classic"def run(*tests):    Flags._instance = None                  # a fresh process    for test in tests:        try:            test()            print("pass", test.__name__)        except AssertionError:            print("FAIL", test.__name__)run(test_classic, test_new)print("the same tests, other order")run(test_new, test_classic)
Both tests are correct. Only one order passes.
Edit and run it in your browser

A common repair is a reset() for tests. It works until two tests run side by side, and it puts a weapon into production code. Remove the cause instead.

The refactor

From fetching to receiving

Hand it over

An interface with two questions. It belongs to the callers, not to the settings file.

from typing import Protocolclass Settings(Protocol):    def database_url(self) -> str: ...    def is_enabled(self, flag: str) -> bool: ...

Lines 4 to 6

Two questions, because the callers ask two. A wide interface would make every test object wide.

1 of 1

Why it is built this way

  • Start the refactor here: list what is really used. It is usually much less than the class offers.

After the refactor

Checkout+ page()Reports+ source()«interface»Settings+ databaseUrl()+ isEnabled(flag)

1/3Users know an interface

Two classes, two visible needs.

usesimplementsdepends on

Compare with the first diagram: the arrows now point at an interface.