The more formal definition of the LoD states that "Inside of a method M of a class C, data can be accessed in and messages can be sent to only the following objects (namely, method M of an object O may only invoke the methods of the following kinds of objects):
- Parameters of method M
- (itself)this, super
- Data fields (data members) of class C
- Objects created by functions called by M
- Global Variables
- Temporary variables created in method M
public class Demeter { private A a; private B b; // Any method of an object should call only methods // belonging to public void example(B b) { C c = new C(); this.b = b; // itself int num = f(); b.invert(); // passed parameters a = new A(); a.setActive(); // directly held component objects c.print(); // objects created in method } public int f() { //implementation omitted } }
The LoD can also be stated as "use only one dot". What that means is that we can do something like this: foo.someMethod(), however, x.foo.someMethod() will break the LoD.
No comments:
Post a Comment