This is the 10th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
Replacement on the Richter scale
Substitution Principle, LSP
Inheritance should ensure that any property proved about supertype objects also holds for subtype objects
Inheritance must ensure that the properties held by the superclass are still true in the subclasses.
Richter’s substitution principle mainly expounds some principles about inheritance. When to use inheritance and when not to use inheritance. It mainly reflects the relationship between base class and subclass, is a supplement to the open and closed principle, is the specification of concrete steps to achieve abstraction.
The following Demo shows the problems that should be avoided when inheritance occurs:
class Bird { private flyTime: number; constructor(flyTime:number){ this.flyTime = flyTime; } getFlyTime(){console.log(' flyTime: ${this.flytime} '); }} class extends Bird {constructor(fltTime:number){super(fltTime)} getFlyTime(){console.log(' Ostrich can't fly '); } } (()=>{ const ostrich = new Ostrich(12); ostrich.getFlyTime(); }) ();Copy the code
This is fine, but it has a design problem: Ostrich inherits the Bird class and overrides the getFlyTime method, changing the way its parent uses it to calculate time of flight. Such calls are risky and violate the Richter substitution principle. Because the Richter substitution principle is one of the important ways to implement the open and close principle, so the method of modifying the parent class is not extended, but modified operation.
The solution is to remove the inheritance between them. You can create a new base class, add a time-of-flight method and an output property method, and the Bird and Ostrich classes inherit the new base class to implement their respective functions.
How to use inheritance correctly
- A subclass can extend the functionality of its parent class without changing the functionality of the parent class
- When a subclass’s method implements a parent class’s method, the conditions can be enhanced but the functionality should be equivalent,
- Subclasses can add their own unique methods
Richter’s substitution principle works
- It avoids the disadvantage of reduced reusability caused by inheriting a parent class
- It is a guarantee that the action correctness, that is, the parent class will implement the same function, to avoid introducing new errors.
- Enhance the robustness of the program, while changing can be very good compatibility
The resources
- C.biancheng.net/view/1324.h…