2 ms·
If the code snippet returns a local ID object, then calling a method on the ID object doesn't violate the law of Demeter. It can be, in fact, the preferred met
by dhimes 14y ago
If the code snippet returns a local ID object, then calling a method on the ID object doesn't violate the law of Demeter. It can be, in fact, the preferred method in the case that you don't have control over the db object.
If your snippet doesn't return a local id object, then the violating portion should be
idstring = db.findUserBySsNumber(ssNumber).toString();
println("id=" + idstring)
A (perhaps) more clear illustration is when you go the other way with the data. Suppose you want to change the last name of the user. You would want to consider that
id.setLastName('Himes')
db.updateUser(id)
may be preferable to
db.findUserBySsNumber(ssNumber).updateLastName('Himes')
The first case is more robust (but, of course, not infallibly so) to changes in the api for db when, for example, the api providers decide it's too dangerous to throw SSNs around. It's also more robust against changes in the content of id.
These are the kinds of things that OO guidelines can protect against. The tradeoff is added overhead (data objects)-- which means more testing, debugging, etc.
- nessus42 14y agoI'm sorry for not being more clear. `db` is a service and the code snippet is client code. I'm not sure what you mean by a "local object" (unless you are referring to C++'s stack-allocated objects). `Id` is a class defined by the service. The service doesn't know anything about the client code.
- dhimes 14y agoBy local object, I mean an object defined in whatever object the above code is written. But anyway, the guideline takeaway is: work locally. This isn't so important perhaps in the stuff we showed here, but if you had many operations on it, then you risk being fragile to changes in db's api. That's what you are trying to avoid (because they do change, and in ways that can break things). It's probably so obvious now that you're scratching your head trying to figure out what the hell I'm talking about he couldn't be saying something _that_ stupid!. But back when OO was just going mainstream I would imagine that guidelines like these were useful as all the new programmers likely had the same questions and the guidelines answered them.