The principle of substitution Liskov directly implies that preconditions should not be strengthened in subclasses. This is logical (because the overridden method of a subclass for which the input data will be unacceptable will not work correctly / throws an exception). But how then to design the following architecture:
There is a class, say Vehicle (you can make it abstract, it doesn’t matter), it has a virtual Weight method (even if this method does some abstruse calculations for each type of vehicle depending on weight, it’s not so important):
public abstract class Vehicle { public virtual void Weight(int w) { } } Now we have the Motorcycle class, which we inherit from Vehicle, but we have to limit its max mass to say 200 kg.
public class Motorcycle : Vehicle { public override void Weight(int w) { if (w > 200) throw new WeightOverflowException(); } } everything seems fine, logical inheritance, with inheritance of all properties and behavior, but the LSP breaks:
List<Vehicle> list2 = new List<ConsoleApp1.Vehicle>(); list2.Add(new Motorcycle()); foreach (var item in list2) { item.Weight(400); } a WeightOverflowException exception will fly, about which the base class should not know anything at all. How to design such a problem?