Friday, May 31, 2013

Law of Demeter in Java and Scala

Target audience: Beginner
Estimated reading time: 10'


The Law of Demeter for methods requires that a method of an object may only invoke the methods of the following kinds of objects:
 1  The object itself: this
 2  Variables or objects which scope is the class (attributes or variable members)
 3  The method parameters (or arguments)
 4  Variables or objects local to the method
 5  A global variable or object accessible by the object

The advantage of  the Law of Demeter is that applications are easier to maintain and update because objects are less dependent on the member attributes of other objects. Such a advantage is important when using 3rd party libraries or frameworks. Design patterns such as Facade, Adapter or Proxy provide developers with similar benefits.
The main drawback of Law of Demeter is the constant need to create wrappers to isolate the internal structure of other objects adding execution time overhead. Such wrappers, commonly used in large frameworks, relies on interfaces that delegate the actual implementation of functionality to concrete classes.  Aspect programming, attempts to get around this overhead, among other things.

The law of Demeter was very popular in early 1990's when C++ gained acceptance in the software engineering community.

Use case
The following Java and Scala code snippets illustrates the programming idioms that complies and also violates the Law of Demeter. The following Java class that implements a string concatenation complies with the law regarding local, class attributes and methods.

public class StringConcatenation  {
  private String _name = null;
  public String rightUsage(final String s) {
      // Rule 1: Invoke its own method using 'this'
    if( this.isValid(s) ) {
      // Rule 2: Call its own attribute:  '_name'
      StringBuilder buf = new StringBuilder(_name); 
      // Rule 3: Call methods parameter: 's'
      buf.append(s );
      // Rule 4: Call local object : 'buf'
    return buf.toString();

The rightUsage method complies with the Law of Demeter because it is referring to objects, variables or method with either class or local scope. Let's consider the following Scala Trait, Dictionary and class, ScientificDictionary that are provided as part of a 3rd party library. The Translation class uses a specific dictionary (scientific, medical,....) in particular language (English,German..) to translate any document.

sealed trait Dictionary[Language] {  
   def translate[Language](s: String): String 
case class ScientificDictionary[Language] 
   extends Dictionary[Language] { }                
case class MedicalDictionary[Language] 
   extends Dictionary[Language] { }
case class SlangDictionary[Language] 
   extends Dictionary[Language] { }
class Translation[Language](
  var dictionary: Dictionary[Language]
)  {
  def translate[Language](s: String): String = 

The method wrongUsage below violates the Law of Demeter because there is no guarantee that the 3rd party library provider may not alter or remove a reference to Dictionary from the Translation object. There is also no guarantee that the translate method may be removed or deprecated in future releases of the library.

class StringConcatenation(_name: String) {
  def wrongUsage(
    translate: Translation[Spanish], 
    s: String
  ): String = translate._dictionary.translate(s"${_name}$s")

Some code analysis tools can be configured to enforce one or more Demeter rules. At the minimum, these rules should be part of the tool box of software development technical lead responsible for code reviews.

Law of Demeter Wikipedia


  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training India . Nowadays Java has tons of job opportunities on various vertical industry.