SOLID in One Interview: A Full Before/After Refactor
You'll learn to
- -Apply all five SOLID principles, in order, to one messy class and explain each step
- -See the finished design run end to end with a fake repository and a fake notifier
- -Practice narrating the refactor aloud, naming the principle behind every change
Tip: the highlighter is on - just select any text below to mark it. Use the highlighter button up top to change color or turn it off. Highlights are saved on this device only. Log in to save them to your account instead.
Each SOLID principle on its own is straightforward. The real interview skill is applying all five to one messy class, in a sensible order, while explaining your reasoning aloud. A silent refactor earns no credit. First, a one-line reminder of what the letters stand for, in plain words.
- -S, Single Responsibility: a class has one reason to change.
- -O, Open/Closed: add new behavior by adding new code, not by editing working code.
- -L, Liskov Substitution: any subtype must work wherever its parent type is expected.
- -I, Interface Segregation: do not force a class to depend on methods it does not use.
- -D, Dependency Inversion: depend on contracts, not on concrete details.
The Starting Point
Here is one realistic starting class, an OrderProcessor that has picked up every responsibility over several sprints. It validates, charges, stores and notifies, all in one method, and it branches on payment type.
class OrderProcessor:
def process(self, order, payment_type: str):
# validation
if not order.items:
raise ValueError("Empty order")
# payment - branches on type, grows with every new payment method
if payment_type == "credit_card":
charge_credit_card(order.total)
elif payment_type == "paypal":
charge_paypal(order.total)
# persistence - talks directly to MySQL
mysql_connection.execute("INSERT INTO orders ...")
# notification
send_email(order.customer_email, "Order confirmed")Step 1, SRP: Separate the Four Reasons to Change
Validation rules, payment, storage and notification each change for a different reason and for a different stakeholder. Split them into OrderValidator, PaymentProcessor, OrderRepository and OrderNotifier. OrderProcessor becomes a thin conductor that calls each in order.
Step 2, OCP: Remove the Payment-Type Branch
The if/elif on payment_type is the growing-switch smell from the Open/Closed chapter. Replace it with a PaymentStrategy contract and one class per payment method. A new method of payment is then a new class, not a new elif in code every payment type depends on.
Step 3, LSP: Check That Every Strategy Truly Substitutes
Pause and test the new hierarchy. Does every PaymentStrategy charge an amount without surprising a caller that only knows the contract? If a gift-card payment needed a "partial charge" idea that the contract never promised, you catch that now, rather than as a production bug.
Step 4, ISP: Split a Repository That Has Grown Too Wide
Suppose OrderRepository has also collected generate_analytics_report(). Callers that only save and fetch orders should not depend on a reporting method. Move the report into its own contract.
Step 5, DIP: Depend on Contracts at the Top
Finally, OrderProcessor asks for its four collaborators in its constructor, each typed as a contract. The runnable version below is the whole refactored design. It uses an in-memory repository and a console notifier so you can watch it work, and then swaps payment type to show the Open/Closed benefit.
Notice what is now true. OrderProcessor never mentions a database, a card network or an email client. Each of the four collaborators can be swapped, replaced by a fake in a test, or extended with a new implementation, and OrderProcessor never needs to be reopened.
When you narrate this in an interview, name the principle as you apply each step: "this is an SRP split because...", "this removes the OCP violation because...". It shows you are reasoning from principles and not pattern-matching from memory.
After this refactor, the interviewer asks: "How would you unit test OrderProcessor.process() without hitting a real database or a real payment API?"
"I'd set up a test database and a sandbox payment account to run the test against."
"I wouldn't need either - since OrderProcessor depends on the OrderRepository and PaymentStrategy interfaces, I'd inject a fake in-memory repository and a fake payment strategy that just records what it was called with. The test verifies OrderProcessor's orchestration logic in isolation, which is exactly the payoff of applying Dependency Inversion in the first place."
In the OrderProcessor refactor, what specifically triggers applying the Single Responsibility Principle?
Discussion0
Join the Discussion
Sign in to leave comments, reply to others, or like insights.
No comments yet. Be the first to start the thread!