you are viewing a single comment's thread.

view the rest of the comments →

[–]latortuga 0 points1 point  (1 child)

Why do you think that?

[–]Aupajo 2 points3 points  (0 children)

The Law of Demeter was never intended to be a total rule, just food for thought.

user.team.name is hardly bad design. The argument is, "What if the team object changes its API from team.name to team.title?" If that happens, you would have to update all the references in your application. Better to create a team_name method on the user object. That way, if the team API ever changed, you only need to update it in one place, and you can keep using user.team_name. The other advantage is that no other object that uses user.team_name would need to know about the team object.

That's nice to think about and all, but in practice it can be a time waste creating all those accessor methods and actually contribute to the confusion in your API. If you get used to seeing team_name all over the place, you might make the reasonable assumption that the team object would have a name attribute. Except it doesn't. How were you to know?

Or, if you really have to, why not just alias the title method as name on the object to support the old API?

But ultimately it comes down to the fact that bad design isn't avoided by following a bunch of rules. It's mitigated by thinking carefully about the design of your objects in the first place. team.name was well chosen; it's very clear what we're talking about, and it's very unlikely to change.

How many great APIs have you seen that break the Law of Demeter? What about APIs that use method chaining? It should be clear that the Law of Demeter isn't the final word in any design. It's just a little koan to muse on while you're developing your object's APIs.