Complete the code to follow the Law of Demeter by accessing only immediate friends.
class Car { Engine engine; void start() { engine.[1](); } }
The method ignite is a direct action on the immediate friend engine, following the Law of Demeter.
Complete the code to avoid violating the Law of Demeter by not accessing nested objects directly.
class Library { Book book; void printAuthor() { System.out.println(book.[1]()); } }
getPublisher() or deeper.Accessing getAuthor() is allowed because book is a direct friend. Accessing nested objects beyond that would violate the Law of Demeter.
Fix the error in the code to comply with the Law of Demeter by removing chained calls.
class Computer { CPU cpu; void checkStatus() { cpu.[1](); } }
cpu.getFan().getTemperature().Calling start() on cpu is allowed as it is a direct friend. Calling getFan() returns another object, leading to chained calls which violate the Law of Demeter.
Fill both blanks to rewrite the code so it respects the Law of Demeter by delegating calls.
class House { Kitchen kitchen; void clean() { kitchen.[1](); kitchen.[2](); } }
getFridge() or getOven().Calling cleanSink() and cleanFloor() directly on kitchen respects the Law of Demeter by avoiding chained calls.
Fill all three blanks to refactor the code to follow the Law of Demeter by avoiding chained calls.
class School { Classroom classroom; void startClass() { classroom.[1](); classroom.[2]().[3](); } }
getStudents() or chaining deeper than one level.Calling openDoor() directly on classroom and then calling teachLesson() on the teacher obtained via getTeacher() respects the Law of Demeter by limiting access to immediate friends.