This is the 17th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

1. Least Knowledge Principle LKP

Take mall as an example, if our distribution mall AMall needs to obtain a commodity information, one way is to provide two interfaces, JDGoodsService for providing commodity information of JD mall, and one TMGoodsService for providing commodity information of TM mall. AMall calls different interfaces to get commodity information.

This is a violation of Demeter’s law, notice, it’s a violation of Demeter’s law.

Demeter’s law is also known as the principle of least knowledge. The standard definition is:

Only talk to your immediate friends

According to our example above,AMall needs to obtain commodity information, and it should not communicate with JD and TM interfaces directly, but OneMall provides a unified interface for obtaining commodity information. As for whether to obtain JD or TM products, OneMall should worry about it. In the example above, our AMall communicates directly with the specific mall interface, bypassing OneMall, which violates Demeter’s rule.

Demeter’s law tells us how to deal with interface dependencies. Following Demeter’s rule will make the code much easier to extend. For example, if we add a TB mall interface in the future, there will be no need to change it for AMall.

2. Open Close Principle OCP

Or take our OneMall mall as an example, now I have connected with JD mall, TM mall, TB mall, if we want to connect with other malls later, our OneMall mall should be through the extension (increase) class interface to achieve the function, rather than by modifying the interface and class to achieve.

If this can be achieved by extension, it shows that our project design complies with the open and closed principle.

Definition of open close principle:

Software entities like classes,modules and functions should be open for extension but closed for Modifications. (A software entity such as classes, modules, or functions that should be open to extension and closed to modification.)

Code design that follows the open close principle makes it easier to expand.

The open and closed principle is the higher level abstraction of the five design principles before, or the five design principles before is the concrete embodiment of the open and closed principle.

It may be a little convoluted, but we can understand that when we design code, the ultimate goal is to want code to conform to or abide by the open and closed principle, and how to design to conform to the open and closed principle, is to try to abide by the other five design principles!