What is Law of Demeter?

前端 未结 3 1078
慢半拍i
慢半拍i 2021-02-20 10:05

Let\'s start with Wikipedia:

More formally, the Law of Demeter for functions requires that a method m of an object O may

3条回答
  •  北恋
    北恋 (楼主)
    2021-02-20 10:45

    An example for Rule 5 would be:

    public class ClassOne {
        public void method1() {
            classTwo.STATIC_INSTANCE.method2();
        }
    }
    
    class ClassTwo {
        public static final ClassTwo STATIC_INSTANCE = ...;
    
        public void method2() {
        }
    }
    

    Enums basically work this way, and it's ok to access enums.


    Your example:

    user.getName().getLastName();
    

    obviously contradicts the laws, since the object you get from "getName()" will not fall into any of the categories listed. Note: this is wrong even if you are not using chain-calls:

    Name name = user.getName();
    name.getLastName(); // <- this is still wrong
    

    since the object "name" still does not fall into any of the listed categories.

    However things like this are ok:

    reportBuilder.withMargin(5).withFooter(10)
        .withBorder(Color.black).build();
    

    Why is this allowed? Because you either get the same object (the reportBuilder) back each time, or maybe a new object each time if the builder is implemented as immutable. Either way, it falls into law 2 or 3, so it's ok either way.


    Your third question is "how to obey". Well, this is a complex question, but just to start, think about what kind of methods are actually forbidden by the laws!

    Just put the laws into negative: We shouldn't call methods on objects that are already there (because new objects are exempt), and are not my object, or fields of my object, or my parameters. So that leaves objects that are in the fields of other objects!

    So basically that means you shouldn't be able to "get" access to objects that are not you, not in your fields, and not direct parameters. Which I would summarize as "no getters"!

提交回复
热议问题