Recall & Review
beginner
What is the Law of Demeter?
The Law of Demeter is a design guideline that suggests a module should only communicate with its immediate friends and not with strangers. It means an object should only call methods of: itself, its fields, parameters, or objects it creates.
Click to reveal answer
beginner
Why is the Law of Demeter important in system design?
It reduces dependencies between modules, making the system easier to maintain and less fragile. Changes in one part of the system are less likely to break others.
Click to reveal answer
intermediate
Which of the following violates the Law of Demeter?<br>
order.getCustomer().getAddress().getCity()
This violates the Law of Demeter because it accesses a chain of objects beyond immediate friends. The object should not reach through multiple objects to get data.
Click to reveal answer
intermediate
How can you fix a violation of the Law of Demeter?
You can add methods to intermediate objects to hide internal structure. For example, add a method getCity() in Customer that returns the city, so callers don't chain calls.
Click to reveal answer
beginner
What is a real-life analogy for the Law of Demeter?
Imagine you want to know the weather. Instead of asking your friend’s friend’s friend, you ask your friend directly. Your friend then asks their friend and tells you the answer. You don’t talk to strangers.
Click to reveal answer
Which of these is a principle of the Law of Demeter?
✗ Incorrect
The Law of Demeter advises to only communicate with immediate friends (directly related objects).
What problem does the Law of Demeter help to avoid?
✗ Incorrect
It reduces tight coupling by limiting object interactions.
Which code snippet violates the Law of Demeter?
✗ Incorrect
Calling getEmail() on the profile object returned by getProfile() is chaining calls beyond immediate friends.
How can you improve code that violates the Law of Demeter?
✗ Incorrect
Adding methods to intermediate objects encapsulates details and prevents chaining.
The Law of Demeter is also known as:
✗ Incorrect
The Law of Demeter is often called the Principle of Least Knowledge.
Explain the Law of Demeter and why it is useful in designing software systems.
Think about how objects should limit their knowledge about others.
You got /4 concepts.
Describe a scenario where violating the Law of Demeter causes problems and how you would refactor it.
Consider how to hide internal object structure.
You got /4 concepts.