👉 Read the full lesson on DevLadder (free, lesson 4 of 8 in the SOLID Principles with Examples course)
Clients should not be forced to depend on methods they don't use. Split fat interfaces into role interfaces.
// ❌ Fat interface: a basic printer must implement Fax and Scan
public interface IMachine { void Print(Doc d); void Scan(Doc d); void Fax(Doc d); }
public class BasicPrinter : IMachine
{
public void Print(Doc d) { }
public void Scan(Doc d) => throw new NotSupportedException(); // also an LSP smell
public void Fax(Doc d) => throw new NotSupportedException();
}
// âś… Role interfaces
public interface IPrinter { void Print(Doc d); }
public interface IScanner { void Scan(Doc d); }
public interface IFax { void Fax(Doc d); }
public class BasicPrinter2 : IPrinter { public void Print(Doc d) { } }
public class OfficeMachine : IPrinter, IScanner, IFax { /* all three */ }
Continue reading the lesson →
An interview question on SOLID Principles with Examples
Explain the Liskov Substitution Principle with the Rectangle–Square example.
Mathematically a square is a rectangle, but if Square overrides Width/Height setters to keep sides equal, code written for Rectangle (set width 5, height 4, expect area 20) breaks and gets 16. The subtype changed the base's behaviour, which violates LSP. Fix: don't inherit; make both implement IShape with an Area, or make them immutable. Practical LSP violations: overrides throwing NotSupportedException, or a read-only collection deriving from a writable one.
Can you answer these?
- What is the difference between Dependency Inversion, Dependency Injection and Inversion of Control?
- What are the service lifetimes in ASP.NET Core DI and what is a captive dependency?
- Your
NotificationServicesends email via SMTP usingnew SmtpClient()inside the method. The business now wants SMS and WhatsApp too, and tests keep sending real emails. What do you change? - A code review shows
if (shape is Circle) ... else if (shape is Square) ...in five places. What principle is violated and how do you fix it?
The answers, plus 7 more SOLID Principles with Examples interview questions and a mock-interview mode, are free on DevLadder.
Next in the course: D: Dependency Inversion Principle →
Top comments (0)