1. Reduce connections between objects
The single responsibility principle guides us to divide objects into smaller granularities, which can improve the reusability of objects. But more and more objects may have complex connections. If one of the objects is modified, it may affect other objects that refer to it. Objects are coupled together, which may reduce their reusability. In the program, it is not a good thing to have too many "friends" to the target. The stories of "a fire in the city gate will affect the fish in the pond" and "one person breaks the law and implicates the nine tribes" happening from time to time.
The principle of minimum knowledge requires that when designing programs, we should minimize interaction between objects. If two objects do not have to communicate directly with each other, then the two objects do not have direct connection. A common practice is to introduce a third-party object to assume the communication role between these objects. If some objects need to make requests to others, they can be forwarded through third-party objects.
2. The principle of least knowledge in design patterns
The most commonly reflected in the design model are the intermediary model and the appearance model, which we will introduce below.
Intermediary model
It is absolutely impossible for tens of millions of people to calculate odds and wins during the World Cup without a bookmaker as an intermediary. As an intermediary, everyone only has connections with the gambling company. The gambling company will calculate the odds based on everyone's betting situation. Lottery players will get the money from the gambling company if they win, and if they lose, they will pay the money to the gambling company.
The intermediary model embodies the principle of least knowledge well. By adding a mediator object, all relevant objects communicate through the mediator object, rather than referring to each other. Therefore, when an object changes, you only need to notify the intermediary object.
Appearance mode
There are not many scenarios for using appearance mode in JavaScript. The appearance mode mainly provides a consistent interface for a set of interfaces in the subsystem. The appearance mode defines a high-level interface, which makes the subsystem easier to use.
The role of appearance mode is to block the complexity of a set of subsystems to customers. The appearance mode provides customers with a simple and easy-to-use high-level interface, which forwards customer requests to the subsystem to complete specific functional implementation. Most customers can access the subsystem by requesting appearance interfaces. But in a program that uses appearance mode, requesting appearance is not mandatory. If the appearance does not meet the customer's personalized needs, the customer can also choose to go beyond the appearance to directly access the subsystem.
Take the one-click laundry button of a fully automatic washing machine as an example. This one-click laundry button is a look. If it is an old washing machine, customers should manually choose four steps: soaking, washing, rinsing, and dehydration. If this kind of washing machine is eliminated and the rinsing method of new washing machines has changed, we have to learn new rinsing methods. The benefits of fully automatic washing machines are obvious. No matter how the washing machine evolves, what customers need to operate is always just a one-click washing button. This button is the appearance created for a set of subsystems. But if the default rinse time set by the one-click laundry program is 20 minutes, and the customer wants this rinse time to be 30 minutes, then the customer can naturally choose to go beyond the one-click laundry program and manually control the operation of these "subsystems".
The appearance mode is easily confused with ordinary packaging implementations. Both encapsulate some things, but the key to the appearance pattern is to define a high-level interface to encapsulate a set of "subsystems". Subsystems in C++ or Java refer to a collection of classes that collaborate with each other to form a relatively independent part of the system. In JavaScript we usually don't think too much about "classes". If we map appearance patterns into JavaScript, this subsystem should at least refer to a collection of functions.
The simplest appearance pattern should be a code similar to the following:
const A = function () { a1(); a2(); } const B = function () { b1(); b2(); } const facade = function () { A(); B(); } facade();
Now let’s take a look at the relationship between appearance patterns and the principle of least knowledge. There are two main functions of the appearance mode.
- Provides a simple and convenient access portal for a group of subsystems.
- Isolate the connection between customers and complex subsystems, and customers don’t need to understand the details of the subsystem.
From the second point, the appearance pattern is in line with the principle of least knowledge. For example, the one-click laundry button of a fully automatic washing machine separates customers from the subsystems such as soaking, washing, rinsing, and dehydration, so customers don’t need to understand the specific implementation of these subsystems.
Suppose we are writing the program for this old washing machine, and customers must deal with at least four subsystems: soaking, washing, rinsing, and dehydrating. If one of the subsystems changes, the client's calling code must change. After separating the customer from these subsystems through appearance, if the internal part of the subsystem is modified, as long as the appearance remains unchanged, the customer's call will not be affected. Similarly, modifications to appearance will not affect the subsystem, they can be changed separately without affecting each other.
3. Embodiment in the principle of least knowledge
Encapsulation largely expresses the hidden data. A module or object can hide internal data or implementation details, exposing only the necessary interface API for external access. It is inevitable that there will be connections between objects. When an object must refer to another object, we can let the object expose only the necessary interfaces and limit the connections between objects to the smallest range.
At the same time, encapsulation is also used to limit the scope of variables. The scope of variables in JavaScript is:
- A variable is declared globally, or implicitly declared anywhere in the code (without var), then the variable is visible globally;
- Variables are explicitly declared within the function (using var) and are visible within the function.
Limiting the visibility of a variable to a minimum range as possible, the smaller the impact of this variable on other unrelated modules, and the smaller the chance of variables being rewritten and conflicting. This is also a reflection of the broadest principle of least knowledge.
Suppose we want to write a function that calculates product with cache effectfunction mult (){}
, we need an objectconst cache = {}
to save the calculated results.cache
The object is obviously only rightmult
Useful,cache
Object placedmult
The closure formed is obviously more appropriate than putting it in the global scope. The code is as follows:
const mult = (function () { const cache = {}; return function () { const args = (arguments, ','); if (cache[args]) { return cache[args]; } let a = 1; for (let i = 0, l = ; i < l; i++) { a = a * arguments[i]; } return cache[args] = a; } })(); mult(1, 2, 3); // Output: 6
Although adhering to the principle of minimal knowledge reduces dependencies between objects, it is also possible to add some large third-party objects that are difficult to maintain. Like the single responsibility principle, in actual development, whether to choose to make the code comply with the principle of least knowledge depends on the specific environment.
This is the article about the introduction and reflection of the principle of least knowledge of JavaScript. For more relevant content on JS, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!