Composition vs Inheritance: Fixing a Logger Class Explosion

Composition vs inheritance shown by turning 12 logger subclasses into 6 parts: runnable TypeScript, real output, a Java version and trade-offs.

OOP in Practice · Episode 5 of 70 · OOP Foundations · Intermediate · TypeScript 7.0.2

The problem

You’re maintaining the logger of a Node.js order service, where composition vs inheritance stops being a theory question. It began as FileLogger. Then came JsonFileLogger, CloudJsonLogger and BufferedCloudJsonLogger. Now plain text in the cloud is wanted too.

Your task: replace the subclass tree with small parts that combine freely.

Requirements

  • Any format (plain text, JSON) works with any destination (console, file, cloud).
  • Buffering can wrap any destination and sends lines in batches of a chosen size.
  • Messages below the minimum level are dropped.
  • The format of a running logger can be changed without rebuilding it.
  • One failing destination does not stop the others or lose buffered lines.
  • A buffer size below 1 and an empty message are rejected with clear errors.

Constraints and assumptions

  • Single process, in memory. File and cloud are fakes.
  • A fake clock keeps the output repeatable.
  • No npm packages; tsc --strict.

What this tests: composition, inheritance, delegation, interfaces, run-time configuration

Composition vs inheritance, solved for a logger: instead of one subclass per combination, a Logger holds a Formatter and a list of Sink objects and delegates to them. A BufferedSink wraps any sink. Three destinations, two formats and optional buffering need 6 small classes instead of 12 subclasses.

Try it yourself first — hint

List what varies independently: where a line goes, what it looks like, whether it waits in a batch. Make each one an object the logger holds.

Step 1: Identify the objects and responsibilities

Logging classes after the refactor
Class / interface Responsibility Key methods
Formatter (interface) Turns a log entry into one line of text. format()
PlainFormatter, JsonFormatter One output format each. format()
Sink (interface) Delivers a batch of lines somewhere. write(), flush()
ConsoleSink, FileSink, CloudSink One destination each. The file and cloud sinks are in-memory fakes. write()
BufferedSink Wraps any sink and sends lines in batches. Keeps the batch if sending fails. write(), flush(), pending
Logger Filters by level, formats once, hands the line to every sink, records failures. log(), flush(), useFormatter()

Step 2: The naive approach and why it breaks

The tree in miniature. CloudJsonLogger wants JSON, which lives in JsonFileLogger, so it extends that.

class FileLogger {
  readonly lines: string[] = []; // stands in for app.log on disk
  format(level: string, msg: string): string { return `${level} ${msg}`; }
  log(level: string, msg: string): void { this.lines.push(this.format(level, msg)); }
}

class JsonFileLogger extends FileLogger {
  format(level: string, msg: string): string { return JSON.stringify({ level, msg }); }
}

// We want JSON in the cloud, and JSON formatting lives in JsonFileLogger...
class CloudJsonLogger extends JsonFileLogger {
  readonly sent: string[] = [];
  log(level: string, msg: string): void {
    super.log(level, msg); // the only way to reach format() + the file write
    this.sent.push(this.lines[this.lines.length - 1]);
  }
}

const cloud = new CloudJsonLogger();
cloud.log("INFO", "order 1042 paid");
console.log("sent to cloud:", cloud.sent);
console.log("also kept in the local file:", cloud.lines);
console.log("is it a FileLogger?", cloud instanceof FileLogger);

Compiled with tsc --strict and run with node naive.js, it prints:

sent to cloud: [ '{"level":"INFO","msg":"order 1042 paid"}' ]
also kept in the local file: [ '{"level":"INFO","msg":"order 1042 paid"}' ]
is it a FileLogger? true
  • It inherits unwanted behaviour. The cloud logger also writes every line to the local file.
  • It is a FileLogger to the compiler. A log-rotation job that accepts file loggers accepts it too.
  • It depends on the parent’s internals. It reads the last item of lines. If FileLogger.log() ever clears that array first, the cloud gets undefined: the fragile base class problem.
  • The tree multiplies. Three destinations × two formats × buffered or not is 12 classes. A fourth destination makes 16.

Step 3: The design

              +--------------------------------+
              | Logger                         |
              | - formatter: Formatter         |
              | - sinks: Sink[]                |
              | - minLevel, clock              |
              | + log()  + flush()             |
              | + useFormatter()               |
              +---------------+----------------+
                  has-a |              | has-a (0..n)
                        v              v
   +--------------------------+   +------------------------------+
   | <<interface>> Formatter  |   | <<interface>> Sink           |
   | + format(entry): string  |   | + write(lines) + flush()     |
   +-----^-------------^------+   +--^--------^--------^-----^---+
         |             |             |        |        |     |
  PlainFormatter JsonFormatter ConsoleSink FileSink CloudSink|
                                                             |
                                       BufferedSink ---------+
                                       - inner: Sink  (wraps any Sink)

The Gang of Four Design Patterns book states it as “favour object composition over class inheritance”, now known as composition over inheritance.

Brandon Rhodes’ Python Patterns Guide walks through a similar logger explosion in Python. The rule: one class per thing that varies, held by the logger. That is composition. The logger asking a part to do the work is delegation.

Inheritance remains, but only of types. Every sink is a Sink, and the logger calls write() without knowing which one, as in polymorphism in OOP. What goes is inheritance of implementation, extending a class to borrow its code, as in inheritance in Java.

BufferedSink implements Sink and also holds one, so it wraps any destination. That shape is the decorator design pattern.

Step 4: The composition vs inheritance solution in TypeScript

type Level = "DEBUG" | "INFO" | "WARN" | "ERROR";
const RANK: Record<Level, number> = { DEBUG: 10, INFO: 20, WARN: 30, ERROR: 40 };

interface LogEntry { readonly time: string; readonly level: Level; readonly message: string; }

/** Turns an entry into one line of text. */
interface Formatter { format(entry: LogEntry): string; }

/** Delivers lines somewhere. Receives a batch so buffering can save requests. */
interface Sink { readonly name: string; write(lines: readonly string[]): void; flush(): void; }

class PlainFormatter implements Formatter {
  format(e: LogEntry): string { return `${e.time} ${e.level.padEnd(5)} ${e.message}`; }
}

class JsonFormatter implements Formatter {
  format(e: LogEntry): string { return JSON.stringify({ time: e.time, level: e.level, msg: e.message }); }
}

class ConsoleSink implements Sink {
  readonly name = "console";
  write(lines: readonly string[]): void { for (const l of lines) console.log(`  [console] ${l}`); }
  flush(): void {}
}

/** In-memory stand-in for a file, so the demo has no disk side effects. */
class FileSink implements Sink {
  readonly lines: string[] = [];
  constructor(readonly name: string) {}
  write(lines: readonly string[]): void { this.lines.push(...lines); }
  flush(): void {}
}

/** Fake log service: one write() = one network request. */
class CloudSink implements Sink {
  readonly name = "cloud";
  online = true;
  requests = 0;
  readonly received: string[] = [];
  write(lines: readonly string[]): void {
    if (!this.online) throw new Error("cloud unreachable");
    this.requests++;
    this.received.push(...lines);
  }
  flush(): void {}
}

/** Wraps ANY sink and sends lines in batches. Keeps the batch if the send fails. */
class BufferedSink implements Sink {
  private buffer: string[] = [];
  constructor(private readonly inner: Sink, private readonly size: number) {
    if (!Number.isInteger(size) || size < 1) throw new RangeError(`buffer size must be a whole number >= 1, got ${size}`);
  }
  get name(): string { return `buffered(${this.inner.name})`; }
  get pending(): number { return this.buffer.length; }
  write(lines: readonly string[]): void {
    this.buffer.push(...lines);
    if (this.buffer.length >= this.size) this.flush();
  }
  flush(): void {
    if (this.buffer.length === 0) return;
    this.inner.write(this.buffer); // throws -> buffer is kept for the next try
    this.buffer = [];
    this.inner.flush();
  }
}

/** The logger HAS a formatter and sinks; it inherits from nothing. */
class Logger {
  readonly failures: string[] = [];
  constructor(
    private formatter: Formatter,
    private readonly sinks: readonly Sink[],
    private readonly clock: () => string,
    private readonly minLevel: Level = "INFO",
  ) {}
  useFormatter(formatter: Formatter): void { this.formatter = formatter; }
  log(level: Level, message: string): void {
    if (message.trim() === "") throw new Error("log message must not be empty");
    if (RANK[level] < RANK[this.minLevel]) return;
    const line = this.formatter.format({ time: this.clock(), level, message });
    this.each((s) => s.write([line]));
  }
  flush(): void { this.each((s) => s.flush()); }
  private each(action: (s: Sink) => void): void {
    for (const sink of this.sinks) {
      try { action(sink); } catch (err) { this.failures.push(`${sink.name}: ${(err as Error).message}`); }
    }
  }
}

function fakeClock(): () => string {
  let tick = 0;
  return () => `09:00:${String(++tick).padStart(2, "0")}`;
}

console.log("== 1. Development: plain text to the console, DEBUG filtered out ==");
const dev = new Logger(new PlainFormatter(), [new ConsoleSink()], fakeClock());
dev.log("INFO", "server started on port 8080");
dev.log("DEBUG", "cache warmed");
dev.log("WARN", "disk 91% full");

console.log("== 2. Same logger, formatter swapped at run time ==");
dev.useFormatter(new JsonFormatter());
dev.log("ERROR", "payment gateway timeout");

console.log("== 3. Production: JSON, batches of 3 to the cloud, plus an audit file ==");
const cloud = new CloudSink();
const buffered = new BufferedSink(cloud, 3);
const audit = new FileSink("file:audit.log");
const prod = new Logger(new JsonFormatter(), [buffered, audit], fakeClock());
for (const id of [1041, 1042, 1043, 1044]) prod.log("INFO", `order ${id} paid`);
console.log(`cloud requests=${cloud.requests} received=${cloud.received.length} buffered=${buffered.pending} audit lines=${audit.lines.length}`);

console.log("== 4. Edge case: the cloud goes offline mid-batch ==");
cloud.online = false;
prod.log("WARN", "order 1045 retrying card");
prod.log("INFO", "order 1046 paid");
console.log(`failures=${JSON.stringify(prod.failures)} buffered=${buffered.pending} audit lines=${audit.lines.length}`);
cloud.online = true;
prod.flush();
console.log(`back online -> cloud requests=${cloud.requests} received=${cloud.received.length} buffered=${buffered.pending}`);
console.log(`last line in cloud: ${cloud.received[cloud.received.length - 1]}`);

console.log("== 5. Edge case: invalid input is rejected ==");
for (const attempt of [() => new BufferedSink(cloud, 0), () => prod.log("INFO", "   ")]) {
  try { attempt(); } catch (err) { console.log(`${(err as Error).name}: ${(err as Error).message}`); }
}
  • Two small interfaces carry the design. Small interfaces are easy to implement and to fake in tests.
  • implements is a check, not a link. In TypeScript, implements only checks that the class fits the interface; it adds no code.
  • Parts arrive in the constructor. Parameter properties (private readonly sinks) declare and assign each field in one place.
  • A sink receives a batch, so BufferedSink turns three log calls into one cloud request.
  • Failures stay local. Logger.each() records a sink’s error and moves on. BufferedSink clears its buffer only after a successful send.
  • Format is a field, not a class, so useFormatter() swaps it on a live logger.

Step 5: Run it and check the output

== 1. Development: plain text to the console, DEBUG filtered out ==
  [console] 09:00:01 INFO  server started on port 8080
  [console] 09:00:02 WARN  disk 91% full
== 2. Same logger, formatter swapped at run time ==
  [console] {"time":"09:00:03","level":"ERROR","msg":"payment gateway timeout"}
== 3. Production: JSON, batches of 3 to the cloud, plus an audit file ==
cloud requests=1 received=3 buffered=1 audit lines=4
== 4. Edge case: the cloud goes offline mid-batch ==
failures=["buffered(cloud): cloud unreachable"] buffered=3 audit lines=6
back online -> cloud requests=2 received=6 buffered=0
last line in cloud: {"time":"09:00:06","level":"INFO","msg":"order 1046 paid"}
== 5. Edge case: invalid input is rejected ==
RangeError: buffer size must be a whole number >= 1, got 0
Error: log message must not be empty

Tested: TypeScript 7.0.2 / Node.js v22.23.5 — tsc --strict --target es2022 --module commonjs main.ts && node main.js, 2026-11-20. Output above is copied from that run.

In section 4 the second offline call fills the batch, the send fails and one failure is recorded. The audit file still gets both lines. One flush() later delivers all three in a single request.

Why this design works

  • Single responsibility: formatting, delivery and batching each live in one class.
  • Open for extension: a Slack sink is one new class and no edits; see the open/closed principle.
  • Additive growth: 3 + 2 + 1 parts cover all 12 combinations.
  • Encapsulation holds: no class reads another’s fields.
  • Testable: the demo already injects a fake clock and fake sinks, the seed of dependency injection.

Trade-offs, edge cases and when not to use it

Composition vs inheritance for this logger
Criterion Subclass per combination Composed parts
Classes for 3 destinations × 2 formats × buffering 12 6 parts + Logger
Cost of a new destination 4 new subclasses 1 new class
Change format at run time No; build a new object Yes; useFormatter()
Coupling to parent internals High (reads lines) None; only interface calls
Reading the code One class name says everything Wiring is in one place, the constructor call
Forwarding code None; methods are inherited Some; a wrapper forwards to inner (some languages reduce this)

Two edge cases need a decision in real code. While the cloud is down the buffer grows without limit, so add a cap. Lines still buffered at exit are lost unless shutdown calls flush().

It is overkill for a script that logs plain text to the console forever. Inheritance stays fine for a true “is a” where the child works everywhere the parent does, the Liskov substitution principle. My recommendation: compose when two or more things vary independently.

The fix is a known refactoring, Replace Inheritance with Delegation: hold the old parent as a field, forward to it, remove extends.

Interview follow-up questions

How would you make BufferedSink safe to use from several threads?

In the Java version two threads can call write() together. Both may see a full buffer and send the same batch, or one may clear lines the other just added. The simplest fix is one lock around write() and flush(). For high volume, use a queue: callers enqueue and one background writer drains it in batches, keeping network calls off the request path. Either way the change stays inside BufferedSink.

How would you unit test this design?

Test each part alone. A formatter test passes a fixed entry and checks the string. A BufferedSink test wraps a fake sink, writes N lines and counts batches, including the path where the fake throws and nothing is lost. A Logger test injects a fake clock and a recording sink, then checks level filtering and that one failing sink does not stop the others. No test touches a disk or network.

What if each destination needs its own format?

Move the formatter down a level. A small Handler pairs one Formatter with one Sink and a minimum level, and Logger holds a list of handlers. The console gets plain text while the cloud gets JSON. It is still composition, one layer deeper. Routing through a chain of handlers is covered in the logger low level design episode.

The same solution in Java

Show the Java version
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

public class Main {
    public static void main(String[] args) {
        int[] tick = {0};
        Supplier<String> clock = () -> String.format("09:00:%02d", ++tick[0]);

        System.out.println("== Development: plain text, DEBUG filtered, then JSON at run time ==");
        Logger dev = new Logger(new PlainFormatter(), List.of(new ConsoleSink()), clock, Level.INFO);
        dev.log(Level.INFO, "server started on port 8080");
        dev.log(Level.DEBUG, "cache warmed");
        dev.useFormatter(new JsonFormatter());
        dev.log(Level.ERROR, "payment gateway timeout");

        System.out.println("== Production: JSON in batches of 3 to the cloud ==");
        CloudSink cloud = new CloudSink();
        BufferedSink buffered = new BufferedSink(cloud, 3);
        Logger prod = new Logger(new JsonFormatter(), List.of(buffered), clock, Level.INFO);
        for (int id = 1041; id <= 1044; id++) prod.log(Level.INFO, "order " + id + " paid");
        System.out.printf("cloud requests=%d received=%d buffered=%d%n", cloud.requests, cloud.received.size(), buffered.pending());
        prod.flush();
        System.out.printf("after flush: cloud requests=%d received=%d buffered=%d%n", cloud.requests, cloud.received.size(), buffered.pending());
    }
}

enum Level { DEBUG, INFO, WARN, ERROR }

record LogEntry(String time, Level level, String message) {}

interface Formatter { String format(LogEntry e); }

interface Sink { String name(); void write(List<String> lines); default void flush() {} }

final class PlainFormatter implements Formatter {
    public String format(LogEntry e) { return String.format("%s %-5s %s", e.time(), e.level(), e.message()); }
}

final class JsonFormatter implements Formatter {
    public String format(LogEntry e) {
        String msg = e.message().replace("\\", "\\\\").replace("\"", "\\\"");
        return String.format("{\"time\":\"%s\",\"level\":\"%s\",\"msg\":\"%s\"}", e.time(), e.level(), msg);
    }
}

final class ConsoleSink implements Sink {
    public String name() { return "console"; }
    public void write(List<String> lines) { lines.forEach(l -> System.out.println("  [console] " + l)); }
}

final class CloudSink implements Sink {
    boolean online = true;
    int requests = 0;
    final List<String> received = new ArrayList<>();
    public String name() { return "cloud"; }
    public void write(List<String> lines) {
        if (!online) throw new IllegalStateException("cloud unreachable");
        requests++;
        received.addAll(lines);
    }
}

final class BufferedSink implements Sink {
    private final Sink inner;
    private final int size;
    private final List<String> buffer = new ArrayList<>();
    BufferedSink(Sink inner, int size) {
        if (size < 1) throw new IllegalArgumentException("buffer size must be >= 1, got " + size);
        this.inner = inner;
        this.size = size;
    }
    public String name() { return "buffered(" + inner.name() + ")"; }
    int pending() { return buffer.size(); }
    public void write(List<String> lines) {
        buffer.addAll(lines);
        if (buffer.size() >= size) flush();
    }
    public void flush() {
        if (buffer.isEmpty()) return;
        inner.write(List.copyOf(buffer)); // throws -> buffer is kept
        buffer.clear();
        inner.flush();
    }
}

final class Logger {
    private Formatter formatter;
    private final List<Sink> sinks;
    private final Supplier<String> clock;
    private final Level minLevel;
    final List<String> failures = new ArrayList<>();
    Logger(Formatter formatter, List<Sink> sinks, Supplier<String> clock, Level minLevel) {
        this.formatter = formatter;
        this.sinks = List.copyOf(sinks);
        this.clock = clock;
        this.minLevel = minLevel;
    }
    void useFormatter(Formatter f) { this.formatter = f; }
    void log(Level level, String message) {
        if (message.isBlank()) throw new IllegalArgumentException("log message must not be empty");
        if (level.compareTo(minLevel) < 0) return;
        String line = formatter.format(new LogEntry(clock.get(), level, message));
        for (Sink s : sinks) {
            try { s.write(List.of(line)); } catch (RuntimeException ex) { failures.add(s.name() + ": " + ex.getMessage()); }
        }
    }
    void flush() {
        for (Sink s : sinks) {
            try { s.flush(); } catch (RuntimeException ex) { failures.add(s.name() + ": " + ex.getMessage()); }
        }
    }
}
== Development: plain text, DEBUG filtered, then JSON at run time ==
  [console] 09:00:01 INFO  server started on port 8080
  [console] {"time":"09:00:02","level":"ERROR","msg":"payment gateway timeout"}
== Production: JSON in batches of 3 to the cloud ==
cloud requests=1 received=3 buffered=1
after flush: cloud requests=2 received=4 buffered=0

A Java class has exactly one direct superclass, so “JSON and cloud and buffered” cannot be three parents. Interfaces give multiple inheritance of type, not state, which is all Sink needs. LogEntry is a record, and records are implicitly final. Tested: OpenJDK 21.0.13 — java Main.java, 2026-11-20.

Practice: extend it yourself

  1. Add a CsvFormatter (time,level,"message", inner quotes doubled). Expected behaviour: it works with every sink and no existing class changes.
  2. Give BufferedSink a maxPending limit that drops the oldest line. Expected behaviour: limit 4, cloud offline for 6 lines → pending is 4, 2 dropped.
  3. Write a MultiSink that forwards to several sinks. Expected behaviour: new BufferedSink(new MultiSink([cloud, audit]), 3) batches both with one buffer.
  • Composition vs inheritance is “has a” versus “is a”; composed parts are chosen when the object is built.
  • Independent axes of change multiply subclasses (3 × 2 × 2 = 12 loggers) but only add composed parts (3 + 2 + 1 = 6).
  • Delegation means forwarding work to a part you hold.
  • Extending a class to borrow code ties you to its internals.
  • Interfaces still give polymorphism without inheriting any implementation.
  • Composition costs some forwarding code and explicit wiring.

Frequently Asked Questions

What is the difference between composition and inheritance?

Inheritance says a class is a kind of another class and reuses its code through extends. Composition says an object has other objects and calls them. Inheritance is fixed when the class is written; composition is chosen when the object is built, so parts can be swapped and tested alone.

Why is composition preferred over inheritance?

Each new axis of variation multiplies subclasses, while composition adds one small class per option. Composed objects can change behaviour at run time and do not depend on a parent’s internals. It is a default, not a ban.

When should I use inheritance instead of composition?

When the child truly is a kind of the parent, works everywhere the parent is expected, and the parent was designed to be extended. A small, stable hierarchy is fine. If you only want to reuse a few methods, compose instead.

Is the decorator pattern a form of composition?

Yes. A decorator implements the same interface as the object it wraps, holds a reference to it, and adds behaviour around the forwarded call. BufferedSink in this episode is a decorator that adds batching to any Sink.

Does composition mean writing a lot of forwarding code?

Sometimes. A wrapper that exposes every method of the wrapped object needs a one-line forward for each. Small interfaces avoid most of it, and some languages help, such as Kotlin class delegation and Java default interface methods.

References