JSF Anti-Patterns and Pitfalls
Law of Demeter
Once upon a JavaOne conference, Mathias needed to borrow some money. "Craig", said Mathias, "I owe Martin a beer. Can I borrow five bucks"? Craig obliged, finding himself in an awkward moment as Mathias retrieved Craig's wallet and removed five dollars. "Mathias", said Craig, "if I began storing my money in my shoe, or a purse, you would have to change the way you borrow money from me". "You are right", said Mathias, "my money borrowing logic is coupled to your money hiding logic. Next time I'll ask you for the money, and let you be concerned about where it is stored". Craig knew Mathias was a smart guy and dismissed the incident as a harmless cultural misunderstanding. It wasn't; it was a classic demonstration of the Law of Demeter.
Everyone knows people should not reach into each other's pockets for money [Editor's note: erm… noted!], but many people think it's OK for objects to do it.
// highly sensitive to changes of the domain model
<!-- highly sensitive to changes of the domain model -->
Few experienced developers need to be convinced that the above java method chain, or train wreck, does not observe a basic object oriented principle. But some do not recognize that the equally long EL expression is worse. The luxury of a compilation error is not available because EL is interpreted. MethodNotFoundErrors and NullPointerExceptions are common with view templates like this. Refactoring is a pain because EL is loosely typed. When EL expressions become five or six segments long it couples the view template to the model. EL expressions should take advantage of encapsulation, just like plain Java.
<!-- encapsulated, insensitive to changes -->
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)