Thursday, April 29, 2010

Talk to friends, not to strangers.

There is a well-known heuristic called the Law of Demeter .

Law of Demeter says that a method f of a class C should only call the methods of these:
• C
• An object created by f
• An object passed as an argument to f
• An object held in an instance variable of C

The method should not invoke methods on objects that are returned by any of the
allowed functions. In other words, talk to friends, not to strangers

Sample Violation : final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();

If the code had been written as follows, then we probably wouldn’t be asking about Demeter violations.

final String outputDir = ctxt.options.scratchDir.absolutePath;

This issue would be a lot less confusing if data structures simply had public variables
and no functions, whereas objects had private variables and public functions

-- Clean Code by Robert Martin

No comments:

Post a Comment