Common places where LSP is violated, with fixes. 1. Subclass throws for an inherited operation public class FileStorage { public virtual void Delete(string path) { ... } } public class ReadOnlyStorage : FileStorage { public override void Delete(string path) => throw new NotSupportedException(); } Any cleanup code that accepts FileStorage now fails at runtime. Fix: separate capabilities with interfaces: public interface IFileReader { Stream Open(string path); } public interface IFileWriter { void Save(string path, Stream data); void Delete(string path); } ReadOnlyStorage implements only IFileReader, and cleanup code depends on IFileWriter, so the compiler prevents misuse. 2. Subclass changes expected behaviour (Rectangle and Square) A mutable Square that forces equal sides breaks code that sets width and height independently. Fix: do not inherit; use an IShape interface with Area(), or immutable types. 3. Stronger preconditions in the subtype public class OrderProcessor { public virtual void Process(Order o) { ... } } public class InternationalOrderProcessor : OrderProcessor { public override void Process(Order o) { if (o.CustomsCode is null) throw new ArgumentException("Customs code required"); // new requirement ... } } Callers that pass valid domestic orders through the base type suddenly fail. Fix: validate at a different level (model international orders as a separate type, or make the requirement part of the base contract), or let the processor fetch missing data instead of rejecting it. 4. Weaker postconditions A base cache guarantees Get returns what was Set; a "NoOpCache" subclass returns nothing. If callers rely on the guarantee, the subtype breaks them. Fix: make the contract explicit ("may return null; caller must handle a miss") so both implementations honour it. 5. Silently ignoring calls An override that does nothing (for example a logger subclass ignoring Error calls) hides failures. How to apply LSP in practice - Design base classes and interfaces around behaviour contracts, and document them (inputs, outputs, exceptions). - Prefer composition and small interfaces over deep inheritance. - Write contract tests that run the same test cases against every implementation of an interface. - Watch for code smells: is or as checks on subtypes, NotImplementedException, and comments like "do not call this on X".
Ravindra Wadile · · 0 likes