Revisited the six principles of object-oriented design. Six principles combined with 23 design patterns help us write high-quality code with low coupling and high scalability.
Six principles of object orientation
- Single Responsibility
Each class is a collection of closely related instance variables and methods. (For a class, there should be only one reason for its change. Simply put, a class should be a set of highly related functions and data encapsulation.) - Interface isolation A
client should not rely on interfaces it does not need. Relationships between classes should be built on a minimal interface.
Split very large and bloated interfaces into smaller and more specific interfaces. - Liskov substitution The place where the
parent class appears must be able to be replaced by the subclass, and vice versa, not necessarily. - Dependency inversion
High-level modules (callers) do not depend on low-level (concrete implementation classes), details (implementation classes) depend on abstractions (abstract classes or interfaces), and abstractions do not depend on details.
Inter-module dependencies occur through abstraction, and no direct dependencies occur between implementation classes. Dependencies arise through abstract classes or interfaces. - Demeter
is also known as the principle of least knowledge. A class should know the least about the classes it needs to couple or call. The caller or dependency only needs to know the methods it needs, and nothing else. - Open-Closed Principle Open
for extension, closed for modification.
Try to embrace change by extending classes. Once the program is developed, the implementation of a class in the program should only be modified due to errors. New or changed features should be implemented by creating different classes. New classes can be implemented by inheriting classes.