SOLID and Clean Design

Apply the five SOLID principles plus DRY, KISS and YAGNI to write classes that are easy to extend, test and explain in a design round.

Intermediate · about 6 hours · difficulty 3/5

Learn first: OOP Principles

SOLID is a set of five guidelines for keeping object-oriented code flexible. In LLD and machine coding rounds, interviewers do not want the acronym recited; they watch whether your design naturally follows it.

The five principles

  • S, Single Responsibility: a class should have one reason to change. An Invoice that also emails itself and writes to the database has three reasons.
  • O, Open/Closed: open for extension, closed for modification. Adding a new discount type should mean adding a class, not editing a growing if/else chain.
  • L, Liskov Substitution: a subclass must work anywhere its parent is expected. The classic violation is Square extends Rectangle breaking setWidth.
  • I, Interface Segregation: many small interfaces beat one fat one. A Printer should not force a fax() method on devices that cannot fax.
  • D, Dependency Inversion: high-level logic depends on abstractions, not concrete classes. OrderService takes a PaymentGateway interface, so tests can pass a fake.

Companion rules

  • DRY: do not repeat knowledge (but two similar-looking lines are not always duplication).
  • KISS and YAGNI: build what the requirement needs today. Over-engineering is a common LLD mistake.
  • Meaningful names, small functions, and no hidden side effects.

How to practise

Take an old project and look for a class that changes for many reasons or a long switch on type. Refactor it using one principle at a time and notice how tests become easier.

Good enough to move on: for each letter you can show a small "before" snippet that violates it and an "after" snippet that fixes it.

Key concepts

  • Single Responsibility
  • Open/Closed
  • Liskov Substitution
  • Interface Segregation
  • Dependency Inversion and injection
  • DRY, KISS, YAGNI
  • Code smells and refactoring

Mini project

Write a deliberately messy discount calculator (one class, a switch on customer type, direct database calls), then refactor it in five commits, one per SOLID principle, with unit tests that use a fake repository.

Check yourself

Why does Square extending Rectangle violate Liskov Substitution, and how would you model the two shapes instead?

Free resources