CS535 Object-Oriented Programming & Design
Fall Semester, 1996
Doc 32, Law of Demeter
[To Lecture Notes Index]
San Diego State University -- This page last updated Dec 10, 1996
Contents of Doc 32, Law of Demeter
- References
- Principles for Achieving Modularity
- Law of Demeter1
Meyer, Object-Oriented Software Construction, 1988
Lieberherr, Holland, Riel, Object-Oriented Programming: An Objective Sense of
Style, OOPSLA 1988 Proceedings
Few Interfaces
Every module should communicate with as few others as possible
Required for:
- Continuity
- Protection
Small Interfaces
Modules should exchange as little information as possible
Required for:
- Continuity
- Protection
Counter-example:
- Fortran Garbage Common Block
Principles for Achieving Modularity
Explicit Interfaces
Communication between modules must be obvious from the text of the modules
Required for:
Decomposability Composability Continuity Understandability
Counter-example:
- Aliasing with pointers
Information Hiding
All information about a module should be private unless it is specifically
declared public
Required for:
Decomposability Composability Continuity Understandability
Weak Form
Inside of a method M of a class C, data can be accessed in and messages can be
sent to only the following objects:
- Parameters of method M
- this, super
- Data fields of class C
- Global variables
- Temporary variables created in method M
- Objects created by functions called by M
Law of Demeter
Strong Form
* Use accessor function to access data members defined in parent classes
Law of Demeter Example
class Inside {
Instructor boring = new Instructor();
int pay = 5;
public Instructor getInstructor() {
return boring;
}
public Instructor getNewInstructor() {
return new Instructor();
}
public int getPay() {
return pay ;
}
other public & private methods
}
class C {
Inside test = new Inside();
public void badM() {
test.getInstructor().fired();
}
public void goodM() {
test.getNewInstructor().hired();
}
public int goodOrBadM() {
return getpay() + 10;
}
}
Correcting badM
class Inside {
Instructor boring = new Instructor();
int pay = 5;
public Instructor fireInstructor() {
boring.fired();
}
public Instructor getNewInstructor() {
return new Instructor();
}
public int getPay() {
return pay ;
}
other public & private methods
}
class C {
Inside test = new Inside();
public void reformedBadM() {
test.fireInstructor();
}
public void goodM() {
test.getNewInstructor().hired();
}
public int goodOrBadM() {
return getpay() + 10;
}
}
Law of Demeter
Benefits
* Coupling control
- Reduces data coupling
* Information hiding
- Prevents a method from directly retrieving a subpart of an object
-
* Information restriction
- Restricts the use of methods that provide information
* Few interfaces
- Restricts the classes that can be used in a method
* Small interfaces
- Restricts the amount of information passed in a method
* Explicit interfaces
- Explicitly states which classes can be used in a method