Friday, October 9, 2020

Law of Demeter in Java and Scala

Target audience: Beginner
Estimated reading time: 3'

In this article, we shed light on a set of principles frequently bypassed by software engineers: The Law of Demeter, also known as the principle of least knowledge. This design guideline, pivotal in crafting software, especially within the object-oriented paradigm, underscores the essence of minimalism. It posits that an object should make minimal assumptions about the structure or attributes of other entities. In essence, a module should be privy only to the information and resources imperative for its intended function.


Introduction

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'
      buf.append("\n");
    }
     
    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 =  dictionary.translate(s}
}

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.

Reference

Law of Demeter Wikipedia


---------------------------
Patrick Nicolas has over 25 years of experience in software and data engineering, architecture design and end-to-end deployment and support with extensive knowledge in machine learning. 
He has been director of data engineering at Aideo Technologies since 2017 and he is the author of "Scala for Machine Learning" Packt Publishing ISBN 978-1-78712-238-3