Design principal: Understand Law of Demeter

For a good software design, it is very important to have “loosely coupled” classes. A coupling may be defined as the degree of inter dependency exists between software modules. The more coupling between the components in an application, it is harder to modify and maintain it over a period of time.

When we follow proper design principle in our day to day development and based on that do the refactoring of our code, it definitely leads much clean, readable and more maintainable code.

Understanding Principle

  • The object class C itself
  • Members of class C
  • An argument of the method M
  • Object created within the method M
  • Global objects

In general terms it is often described this way:

“Only talk to your immediate friends.”


“Don’t talk to strangers.”


This Law also improves encapsulation and abstraction while can enhance the test ability of code.

Tips to identify

  • Dots counting
  • Too many wrapper classes

Let’s take a look at below bad code of dots counting in JAVA:


In short, the Law of Demeter aims to keep away from doing things like this and try to make it simpler like this:



Now to fix this violation, we have shifted the validation of primaryEmailAddress and mobile within Employee object method, named as isValidPrimaryEmailAddress () and isValidMobile().

You can find a basic code of above explanation from GitHub.


It is hard to follow the design rules but once understand them properly, the benefits are obvious.

Thanks for reading. To help others please click ❤ to recommend this article if you found it helpful. Stay tuned for upcoming articles. For any quires or suggestions, feel free to hit me on Twitter Google+

“Power is gained by sharing knowledge, not hoarding it”

Check out my blogger page for more interesting topics on Software development.

Senior Software Engineer at Mastercard. Dreamer and Achiever..

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store