SoC

SoC — Separation of Concerns

"…what I sometimes have called 'the separation of concerns'… is yet the only available technique for effective ordering of one's thoughts." — Edsger W. Dijkstra, On the role of scientific thought (EWD447, 1974) — the source of the term.


Core idea

Every module (function, class, file) should have one zone of responsibility. The classic split in any program: I/O ↔ business logic ↔ presentation — keep them apart.


Why it matters

When everything is mixed The consequence
Logic + I/O Cannot test the formula without files / DB / network
Logic + presentation Cannot output the same result as JSON, HTML, and console
Parsing + validation + storage A format change breaks everything at once
All in one file A one-feature change requires git blame across the whole file

Three classic layers

┌────────────────────────────────────┐
│  PRESENTATION  (how to show)       │  HTML, JSON, CLI, log
├────────────────────────────────────┤
│  LOGIC         (what to do)        │  rules, formulas, decisions
├────────────────────────────────────┤
│  I/O           (where data lives)  │  file, DB, network, user
└────────────────────────────────────┘

Dependencies point from the edges to the center: presentation and I/O both depend on the logic (through interfaces / ports). Logic should not know about specific I/O or presentation. That is what makes it testable and portable.


Example 1: mixing I/O and logic

❌ Bad

def process_invoice():
    with open("invoice.json") as f:                  # I/O input
        data = json.load(f)
    total = data["qty"] * data["price"] * 1.20       # LOGIC
    print(f"Total: {total:.2f} UAH")                 # PRESENTATION
    with open("result.txt", "w") as f:               # I/O output
        f.write(str(total))

Problems:

✅ Good

# --- LOGIC (pure, isolated) ---
def calculate_total(qty: int, price: float, vat: float) -> float:
    return qty * price * (1 + vat)

# --- I/O ---
def load_invoice(path: str) -> dict:
    with open(path) as f:
        return json.load(f)

def save_result(path: str, value: float) -> None:
    with open(path, "w") as f:
        f.write(f"{value:.2f}")

# --- PRESENTATION ---
def format_for_console(value: float) -> str:
    return f"Total: {value:.2f} UAH"

# --- ORCHESTRATION (glues the layers) ---
def process_invoice(input_path: str, output_path: str) -> None:
    data = load_invoice(input_path)
    total = calculate_total(data["qty"], data["price"], vat=0.20)
    print(format_for_console(total))
    save_result(output_path, total)

Now the formula is one line to test:

assert calculate_total(2, 100, 0.20) == 240

Example 2: mixing logic and presentation

❌ Bad

def user_status(user) -> str:
    if user.is_blocked:
        return "<span class='red'>BLOCKED</span>"
    if user.is_premium:
        return "<span class='gold'>★ Premium</span>"
    return "<span>Regular</span>"

Great for a web page. What about the CLI? The log? The API? You will end up writing three more functions with the same rules.

✅ Good

# Logic: returns a CATEGORY, not a look
def user_status(user) -> str:
    if user.is_blocked:
        return "blocked"
    if user.is_premium:
        return "premium"
    return "regular"

# Presentations live separately
def status_html(status: str) -> str: ...
def status_console(status: str) -> str: ...
def status_json(status: str) -> dict: ...

Example 3: a class with several responsibilities

❌ Bad

class User:
    def __init__(self, name, email):
        self.name = name
        self.email = email

    def save_to_db(self): ...        # I/O
    def send_welcome_email(self): ...# external service
    def to_html(self): ...           # presentation
    def validate(self): ...          # business rules

The class knows about the DB, the email service, HTML, and the rules. Change any of those and you touch User.

✅ Good

class User:                  # data + invariants only
    name: str
    email: str

class UserRepository:        # I/O — storage
    def save(self, user: User) -> None: ...

class EmailService:          # I/O — external integration
    def send_welcome(self, user: User) -> None: ...

class UserPresenter:         # presentation
    def to_html(self, user: User) -> str: ...

(This anticipates SRP from SOLID.)


Functional Core, Imperative Shell

A popular architectural strategy (Gary Bernhardt, 2012):

┌──────────────────────────────────────┐
│  IMPERATIVE SHELL                    │  ← I/O, mutations, side effects
│  - reads files / network / DB        │
│  - orchestrates                      │
│  - validates inputs (fail-fast)      │
│                                      │
│   ┌──────────────────────────────┐   │
│   │  FUNCTIONAL CORE             │   │  ← pure functions
│   │  - business logic            │   │  ← easy to test
│   │  - rules, formulas, decisions│   │  ← easy to port
│   └──────────────────────────────┘   │
└──────────────────────────────────────┘

Everything complex lives in the core, without I/O. Everything "dirty" (I/O) lives in a thin shell around it.


How to recognise multiple responsibilities

"One change" test:

If one change drags edits across several places, the responsibilities are likely mixed.

The "and" description: If you describe the function as "it loads data and computes and displays and saves" — that is four functions.


Rules of thumb

  1. A function should do one whole thing. If the name contains "and", split it.
  2. I/O at the edges, logic in the centre. No open(), requests.get(), or print() inside functions that compute.
  3. One module = one topic. parsing.py, pricing.py, storage.py — not utils.py.
  4. Presentation is a separate layer. Logic returns data or categories, not formatted strings.
  5. Tests are the litmus test. If testing a formula requires spinning up a DB, something is off.

One-line summary

Separate what changes for different reasons. I/O ≠ logic ≠ presentation.