Back to blog

cat blog/les-principes-solid-en-pratique-a-partir-de-vrais-commentaires-de-revue.md

SOLID principles in practice, from real code review comments

Solution Architect

SOLID principles in practice, from real code review commentsSOLID principles in practice, from real code review comments
Contents
  1. S: one reason to change
  2. O: add without modifying
  3. L: replace without surprises
  4. I: depend only on what you use
  5. D: depend on abstractions
  6. When SOLID becomes too much
  7. Up next
  8. Sources

In the previous article, The design patterns I use every day, almost every example applied the same handful of ideas: one class for one responsibility, add without modifying, depend on interfaces. These ideas have a name: SOLID, five principles formulated by Robert C. Martin in the early 2000s.

I won't present them theoretically. I start from code review comments like the dozens I've written, and show the code before and after. The point of SOLID isn't reciting the five letters, it's turning "I don't like this code" into "this code breaks this principle, and here's what it will cost".

Letter

Principle

In one sentence

S

Single Responsibility

A class has only one reason to change

O

Open/Closed

You add behavior without modifying existing code

L

Liskov Substitution

One implementation can replace another without surprises

I

Interface Segregation

No class depends on methods it doesn't use

D

Dependency Inversion

Business code depends on abstractions, not concrete tools

S: one reason to change

"This service computes the invoice, generates the PDF and sends it by email."

The single responsibility principle doesn't say "one class = one method". It says a class should have only one reason to change. Here there are three: a calculation rule that evolves, a layout to redo, an email provider that changes.

// Before: three reasons to change in the same class
final class InvoiceService
{
    public function send(Order $order): void
    {
        $total = $order->lines->sum(fn ($l) => $l->price * $l->quantity) * 1.18;
        $pdf = Pdf::loadView('invoices.show', compact('order', 'total'))->output();
        Mail::to($order->customer)->send(new InvoiceMail($pdf));
    }
}
// After: each class has a single reason to change
final class InvoiceCalculator { public function total(Order $order): Money { /* ... */ } }
final class InvoicePdfRenderer { public function render(Order $order, Money $total): string { /* ... */ } }

final class SendInvoice
{
    public function __construct(
        private InvoiceCalculator $calculator,
        private InvoicePdfRenderer $renderer,
    ) {}

    public function handle(Order $order): void
    {
        $total = $this->calculator->total($order);
        $pdf = $this->renderer->render($order, $total);
        Mail::to($order->customer)->send(new InvoiceMail($pdf));
    }
}

The calculation can now be tested without generating a PDF, and the VAT rate (18% in Togo) no longer lives in the middle of sending an email.

O: add without modifying

"Every new notification channel modifies this switch."

A class should be open for extension, but closed for modification. If adding a case forces you to touch code that already works, every addition risks breaking what exists.

The answer is almost always the Strategy pattern from the previous article. In NestJS, injection even lets you register channels without the service knowing them one by one:

export interface NotificationChannel {
  supports(channel: Channel): boolean;
  send(user: User, message: string): Promise<void>;
}

@Injectable()
export class NotificationService {
  constructor(
    @Inject('NOTIFICATION_CHANNELS')
    private readonly channels: NotificationChannel[],
  ) {}

  async notify(user: User, channel: Channel, message: string) {
    const handler = this.channels.find((c) => c.supports(channel));
    if (!handler) throw new UnsupportedChannelError(channel);
    await handler.send(user, message);
  }
}

Adding WhatsApp means writing a WhatsAppChannel class and adding it to the module's list. NotificationService no longer changes.

L: replace without surprises

"This payment gateway throws on refund()."

The Liskov substitution principle says an implementation must be able to replace any other without the calling code needing to know. As soon as you write if ($gateway instanceof ...) or an inherited method throws "not supported", the contract is broken.

interface PaymentGateway
{
    public function charge(Order $order): PaymentResult;
    public function refund(Payment $payment): RefundResult;
}

final class CashOnDeliveryGateway implements PaymentGateway
{
    public function charge(Order $order): PaymentResult { /* ... */ }

    public function refund(Payment $payment): RefundResult
    {
        // The contract promises a refund this class can't perform
        throw new LogicException('Refund impossible for cash on delivery.');
    }
}

The code refunding an order works with every gateway… except one, and you only find out in production. The problem isn't this class, it's an interface that promises too much. Which leads straight to the next principle.

I: depend only on what you use

"Why does this class have to implement payout() when it only collects payments?"

The interface segregation principle recommends several small interfaces rather than one big one. Split by actual capabilities:

interface ChargesPayments { public function charge(Order $order): PaymentResult; }
interface RefundsPayments { public function refund(Payment $payment): RefundResult; }

final class CardGateway implements ChargesPayments, RefundsPayments { /* ... */ }
final class CashOnDeliveryGateway implements ChargesPayments { /* ... */ }

final class RefundOrder
{
    // This use case only accepts what can refund:
    // the mistake becomes impossible to write, instead of discovered in production
    public function __construct(private RefundsPayments $gateway) {}
}

By fixing I, we also fixed L: no class promises what it can't do anymore. In Flutter, it's the same logic when a read-only screen receives only an OrderReader rather than the full repository with its write methods.

D: depend on abstractions

"You're calling new TwilioClient() directly in the use case."

The dependency inversion principle says business code must not depend on tools, but on abstractions, and the tools adapt to those abstractions. It's what makes the adapters from the previous article possible, and tests without a network.

All three frameworks provide a container to bind the abstraction to its implementation, in a single place:

// Laravel — AppServiceProvider
$this->app->bind(SmsSender::class, TwilioSmsAdapter::class);

// The use case only knows the interface
final class SendOtp
{
    public function __construct(private SmsSender $sms) {}
}
// NestJS — a token for the interface, the implementation chosen in the module
export const SMS_SENDER = Symbol('SMS_SENDER');

@Module({
  providers: [{ provide: SMS_SENDER, useClass: TwilioSmsAdapter }],
})
export class NotificationsModule {}

@Injectable()
export class SendOtp {
  constructor(@Inject(SMS_SENDER) private readonly sms: SmsSender) {}
}
// Flutter — get_it binds the domain contract to the data layer
getIt.registerLazySingleton<OrderRepository>(
  () => OrderRepositoryImpl(getIt<OrdersApi>(), getIt<OrdersCache>()),
);

Why a token in NestJS? TypeScript interfaces disappear at compile time: the container can't use them as keys. The Symbol plays that role.

The benefit shows immediately in tests: I replace SmsSender with a fake that records messages, without ever calling the real provider.

public function test_it_sends_an_otp(): void
{
    $fake = new FakeSmsSender();
    $this->app->instance(SmsSender::class, $fake);

    app(SendOtp::class)->handle('+22890000000');

    $this->assertCount(1, $fake->sent);
}

When SOLID becomes too much

Applied to the letter, the five principles can produce the opposite of what they aim for: code scattered across dozens of tiny classes, where you open eight files to follow one action. My guardrails:

  • An interface is justified by a real need: a second implementation, or a fake in tests. Not "just in case".

  • Single responsibility is judged at the business level, not line by line. A coherent 80-line class beats four 20-line classes that only make sense together.

  • Open/closed applies to areas that move. Code that hasn't changed in two years doesn't need to be extensible.

  • The framework already does part of the job. Form Requests, Policies or NestJS modules already apply S and D: no need to stack a layer on top.

SOLID is a compass, not a rulebook. In review, it mostly serves to name a problem and estimate what it will cost, so we can decide together whether it's worth fixing now.

Up next

Dependency inversion is the foundation of a whole architecture: Clean Architecture, where business logic depends on nothing, and the interface and database are mere details. The next article applies it step by step to a Flutter app.

Sources

  • Robert C. Martin, Clean Architecture: A Craftsman's Guide to Software Structure and Design, Prentice Hall, 2017

  • Robert C. Martin, Agile Software Development, Principles, Patterns, and Practices, Prentice Hall, 2002

Does this concern you? The service that answers itTechnical leadership

Share:

subscribe --blog

Get new posts by email

One email per new post, nothing else. Unsubscribe in one click.

Your address is only used to send you new posts. Privacy