This is the 27th day of my participation in the August Genwen Challenge.More challenges in August

What is Demeter’s rule?

The Law of Demeter, also known as The Least Knowledge Principle, states that an object should know as little as possible about other objects, and only communicate with friends, not strangers. Short for LOD.

It’s a “friend” situation

1) The current object itself (this)

2) An object passed as a parameter to the current object method

3) The object directly referenced by the instance variable of the current object

4) If the instance variable of the current object is an aggregation (such as List< Node >), then the elements in the aggregation are also friends

5) The object created by the current object

Not a “friend” situation

class A{
	public B getB(a) {
		return newB(); }}class B{
	public  void methodB(a) {}}public class NotFriendsTest {
     public  void test(a) {
    	 A a=new A();
    	 B b=a.getB(); // B is not a friend of a
    	 b.methodB();// This is not the case
    	 changeFriends(b);  // We can only write one more method passing b as an argument to the method that calls b
     }
     public void changeFriends(B b) { b.methodB(); }}Copy the code

example

Here simulate the computer shutdown process, close the process -> close the screen -> power off

A violation of Demeter’s rule

public class Person {
    public static void main(String[] args) {
		Computer computer=newComputer(); computer.closeProcess(); computer.closeScreen(); computer.outage(); }}class Computer{
    public void closeProcess(a) {
		System.out.println("Close the process");
	}
    public void closeScreen(a) {
    	System.out.println("Close the screen");
    }
    public void  outage(a) {
    	System.out.println("Power"); }}Copy the code

Correct term

public class Person {
    public static void main(String[] args) {
		Computer computer=newComputer(); computer.close(); }}class Computer{
	 public  void  close(a) {
		 closeProcess();
		 closeScreen();
		 outage();
	 }
	 private void closeProcess(a) {
			System.out.println("Close the process");
		}
	 private void closeScreen(a) {
	    	System.out.println("Close the screen");
	    }
	 private void  outage(a) {
	    	System.out.println("Power"); }}Copy the code

advantages

Reduce class coupling, so that each class minimizes its dependence on other classes

Modules tend to be functionally independent and have little or no dependencies on each other

disadvantages

A large number of small methods are created to pass indirect calls that have nothing to do with business logic. The partial design is simplified, but the communication efficiency of different modules is reduced and it is not easy to coordinate.