Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 25 min · revision 1

SOLID, inversion of control and command-query separation

Master the SOLID design principles, implement Inversion of Control with Dependency Injection, and apply Command-Query Separation to isolate side effects from data retrieval.

Contentsand lesson path

What you will learn

  • Apply SOLID principles to refactor a class design, stating which future change each refactoring makes cheaper.
  • Reduce coupling with the Law of Demeter, command-query separation, inversion of control and a functional core with an imperative shell, and explain what each makes easier to test or change.

01. The SOLID Principles Deconstructed for Architects

The SOLID principles, consolidated by Robert C. Martin in the early 2000s, represent the foundational guidelines of object-oriented and modular system design. Rather than dogmatic academic rules, SOLID principles are economic heuristics designed to ensure codebases remain resilient in the face of inevitable change.

  • Single Responsibility Principle (SRP): Often misunderstood as "a class should do only one thing." Martin clarified the architectural definition: A module should be responsible to one, and only one, actor or stakeholder. If an Employee class contains calculatePay() (demanded by Finance), reportHours() (demanded by Human Resources), and save() (demanded by Database Administrators), it couples three disparate business stakeholders. A change requested by Finance risks breaking reporting for HR. SRP dictates decomposing modules along stakeholder axes.
  • Open-Closed Principle (OCP): Formulated by Bertrand Meyer in 1988: Software entities should be open for extension, but closed for modification. An architect should be able to introduce new business behaviors (e.g., adding a new payment processor or tax calculation algorithm) without altering existing, tested source code. OCP is realized through polymorphic abstractions and plugin boundaries.
  • Liskov Substitution Principle (LSP): Introduced by Barbara Liskov in 1987: Subtypes must be substitutable for their base types without altering system correctness. LSP enforces contract consistency. If class B extends A, client code expecting A must not experience unexpected runtime exceptions, weakened preconditions, or violated postconditions when interacting with B.
  • Interface Segregation Principle (ISP): Clients should not be forced to depend on interfaces they do not use. Bloated, "fat" interfaces couple diverse callers to methods they never invoke. ISP advocates small, focused, role-specific interfaces.
  • Dependency Inversion Principle (DIP): High-level policy modules should not depend on low-level detail modules. Both should depend upon abstractions. Abstractions should not depend on details; details should depend upon abstractions. DIP flips traditional procedural architecture on its head, decoupling business logic from databases, messaging brokers, and third-party web frameworks. By ensuring that core domain policies depend strictly on owned interfaces, an organization can migrate from MySQL to DynamoDB or upgrade HTTP frameworks without modifying core domain models.

02. Inversion of Control, Dependency Injection, and the Composition Root

A common architectural anti-pattern is for high-level business services to instantiate their own low-level dependencies directly using constructor calls (e.g., this.database = new PostgresDatabase()). This tightly couples the business policy to a specific infrastructure implementation, rendering isolated unit testing impossible.

The Hollywood Principle: Inversion of Control (IoC) Inversion of Control inverts traditional control flow: "Don't call us, we'll call you." Instead of an internal class controlling when and how external dependencies are created, an external coordinator assumes responsibility for instantiating and wiring collaborating objects.

Dependency Injection (DI) Mechanisms Dependency Injection is the primary technique for achieving IoC. Dependencies are passed into a component from the outside, predominantly via constructor parameters:

  • Constructor Injection: Declaring required abstractions as constructor parameters. This enforces that an object cannot be constructed in an invalid, half-initialized state.
  • Interface Ownership: Crucially, under true Dependency Inversion, the abstract interface is defined and owned by the client package (the high-level business domain), not by the infrastructure package that implements it. The infrastructure layer depends upon the domain; the domain depends upon nothing.

The Composition Root versus Service Locator Anti-Pattern To prevent dependency wiring logic from sprawling throughout the codebase, enterprise applications establish a Composition Root. The Composition Root is a unified, centralized location as close as possible to the application entry point (e.g., main.py or server.ts) where the entire dependency graph is instantiated, wired together, and executed.

Architects must strictly contrast Dependency Injection with the Service Locator anti-pattern. While a Service Locator also provides dependencies at runtime, it forces domain classes to query a global registry (e.g., ServiceLocator.get(PaymentGateway)). This obscures true component dependencies, turns compile-time missing dependency errors into dangerous runtime crashes, and couples every domain class to the locator registry itself. Pure constructor injection keeps dependencies explicit and verifiable.

03. Command-Query Separation and the Functional Core Pattern

Bertrand Meyer introduced Command-Query Separation (CQS) as a foundational design rule: Every method should either be a command that performs an action (mutating state), or a query that returns data to the caller (free of side effects), but never both.

  • Queries: Return values without mutating visible system state. Because queries are idempotent and side-effect-free, they can be safely executed repeatedly in assertions, logs, and monitoring dashboards.
  • Commands: Mutate state (e.g., debiting an account, writing a database record) but return void (or simple status receipts). Commands execute business actions.

When methods mix commands and queries (e.g., an authenticateUser() method that returns user details while silently incrementing login counters and expiring tokens), developers cannot inspect state without unintentionally changing state.

Functional Core, Imperative Shell Gary Bernhardt expanded CQS into an architectural paradigm: Functional Core, Imperative Shell. In this model, complex business decisions and algorithmic validations are implemented as pure, deterministic functions (the core). The outer boundary (the shell) handles all I/O operations—reading from the database, fetching the clock, listening to HTTP requests—and passes plain data structures into the pure core, drastically simplifying testing.

Python model demonstrating Dependency Inversion and Command-Query Separation
# Demonstrating Dependency Inversion and CQS
from dataclasses import dataclass
from typing import Protocol, Optional

class UserRepository(Protocol):
    def get_user_email(self, user_id: str) -> Optional[str]:
        """Pure Query: reads data without mutating state."""
        ...
    def save_activation_timestamp(self, user_id: str, ts: str) -> None:
        """Pure Command: mutates state without returning data."""
        ...

class UserActivationService:
    def __init__(self, repo: UserRepository) -> None:
        self._repo = repo  # Dependency Injection

    def activate(self, user_id: str, timestamp: str) -> bool:
        email = self._repo.get_user_email(user_id)  # Query
        if not email:
            return False
        self._repo.save_activation_timestamp(user_id, timestamp)  # Command
        return True

class InMemoryUserRepo:
    def __init__(self) -> None:
        self.emails = {"USR-1": "[email protected]"}
        self.activated = {}
    def get_user_email(self, user_id: str) -> Optional[str]:
        return self.emails.get(user_id)
    def save_activation_timestamp(self, user_id: str, ts: str) -> None:
        self.activated[user_id] = ts

repo = InMemoryUserRepo()
service = UserActivationService(repo)
success = service.activate("USR-1", "2026-11-09T12:00:00Z")
print(f"Activation result: {success} | Records: {repo.activated}")

04. Practice check

Practice check · 2 questions

Practice check

Validate your understanding of SOLID design principles, Dependency Inversion, Composition Roots, and Command-Query Separation.

Q1. What is the fundamental architectural requirement of the Dependency Inversion Principle (DIP)?
Q2. Why does Command-Query Separation (CQS) mandate that queries must not alter system state?
Practice only: not graded, not saved, not evidence.

05. Review prompt

Deconstruct the five SOLID design principles (Single Responsibility, Open-Closed, Liskov Substitution, Interface Segregation, Dependency Inversion), defining each through an architectural lens and identifying which future changes each principle makes cheaper.

Explain Inversion of Control (IoC) and Dependency Injection (DI). Contrast direct instantiation with constructor injection, explaining why client interface ownership is essential to true Dependency Inversion.

Describe the role and architectural necessity of the Composition Root in modular application startup.

Finally, articulate Bertrand Meyer's Command-Query Separation (CQS) principle. Explain how combining CQS with the Functional Core, Imperative Shell pattern isolates volatile I/O operations from pure domain decision-making.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check