How to solve the violations of the Law of Demeter?

后端 未结 10 1248
一个人的身影
一个人的身影 2021-01-29 22:23

A colleague and I designed a system for our customer, and in our opinion we created a nice clean design. But I\'m having problems with some coupling we\'ve introduced. I could t

10条回答
  •  后悔当初
    2021-01-29 23:16

    The traditional solution to Demeter violations is "tell, don't ask." In other words, based on your state, you should tell a managed object (any object you hold) to take some action -- and it will decide whether to do what you ask, depending on its own state.

    As a simple example: my code uses a logging framework, and I tell my logger that I want to output a debug message. The logger then decides, based on its configuration (perhaps debugging isn't enabled for it) whether or not to actually send the message to its output devices. A LoD violation in this case would be for my object to ask the logger whether it's going to do anything with the message. By doing so, I've now coupled my code to knowledge of the logger's internal state (and yes, I picked this example intentionally).

    However, the key point of this example is that the logger implements behavior.

    Where I think the LoD breaks down is when dealing with an object that represents data, with no behavior.

    In which case, IMO traversing the object graph is no different than applying an XPath expression to a DOM. And adding methods such as "isThisMedicationWarranted()" is a worse approach, because now you're distributing business rules amongst your objects, making them harder to understand.

提交回复
热议问题