How to solve the violations of the Law of Demeter?

后端 未结 10 1333
一个人的身影
一个人的身影 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:14

    I was struggling with the LoD just like many of you were until I watched The Clean Code Talks" session called:

    "Don't Look For Things"

    The video helps you use Dependency Injection better, which inherently can fix the problems with LoD. By changing your design a bit, you can pass in many lower level objects or subtypes when constructing a parent object, thus preventing the parent from having to walk the dependency chain through the child objects.

    In your example, you would need to pass in AdministrationRoute to the constructor of ProtocolMedication. You'd have to redesign a few things so it made sense, but that's the idea.

    Having said that, being new to the LoD and no expert, I would tend to agree with you and DrJokepu. There are probably exceptions to the LoD like most rules, and it might not apply to your design.

    [ Being a few years late, I know this answer probably won't help the originator, but that's not why I'm posting this ]

提交回复
热议问题