Category Archives: Law of Demeter

Law of Demeter

Todays blog is about the Law of Demeter a.k.a the Principle of Least Knowledge. This information is based off of the article, “Object Oriented Tricks: #2 Law of Demeter”, by Arun Sasidharan on the website “Hackernoon”. The law uses the Tell Don’t Ask principle which states that we may call methods of objects that are: passed as arguments, created locally, instance variables, and globals. In other words, saying that “each unit should only have limited knowledge about other units”, that are closely related to the current unit. Basically the Law of Demeter (LoD) says that it is a bad idea for single functions to know the entire navigation structure of the system, or to have a chain of functions, also known as a “Train Wreck”. The article states, “We want to tell our neighboring objects what we need to have done and depend on them to propagate that message outwards to the appropriate destination”, and that is what we need to do to solve this problem of “Train Wrecks”.

I chose this article because it was one of the first to come up when searching “Law of Demeter”. When I looked into the article it seemed like a reliable source. I also looked up reviews on the website before diving too far into the article. Many people suggested the website in their reviews so I concluded that it was a trustworthy source. The article has paragraphs discussing the law/principle, code snippets to show the before and afters of using the Law of Demeter, and then a final summary at the end to give an overview of everything talked about. I have found that articles with the same elements/structure help me a lot with understanding a new subject.

While reading about the Law of Demeter, it brought me back to a few times where I personally broke the law on projects. There has also been a few times where I have seen people break the Law of Demeter in tutorials, such as the one I watched for the Decorator Pattern. With this article, I learned how to write reliable, clean functions and to use them in a reliable manner. I also learned that it is very difficult to accomplish. As the article states, it is more of a suggestion than a law for that exact reason. Unlike some of the other principles, this is something that we cannot be proficient in in a single day. It is something to set as a longer term goal to improve on. I hope, through practice, to be able to utilize this principle in an efficient manner on future projects.

Source: https://hackernoon.com/object-oriented-tricks-2-law-of-demeter-4ecc9becad85

From the blog CS@Worcester – Austins CS Site by Austin Engel and used with permission of the author. All other rights reserved by the author.