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
employee.getDepartment().getManager().getOffice().getAddress().getZip()
<!-- highly sensitive to changes of the domain model -->
#{employee.department.manager.office.address.zip}
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 -->
#{employee.departmentalManagerOfficeZip}
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)





Comments
Bruce Fancher replied on Mon, 2008/12/15 - 2:20am
Manrico Corazzi replied on Tue, 2008/12/16 - 9:11am
Marc Stock replied on Tue, 2008/12/16 - 2:06pm
+1 to Bruce Fancher
Asking about JSF pitfalls is like sticking your hand in a fire and asking, "What are the pitfalls of sticking your hand in fire?"
Omar Palomino S... replied on Thu, 2008/12/18 - 2:19pm
in response to:
Bruce Fancher
Dzmitry Churbanau replied on Mon, 2008/12/22 - 11:46pm
Bruce Fancher, Manrico Corazzi and Marc Stock: everybody can criticize (read write this is bad and so on) but not everybody can give any valuable reason to it.
So, what is your reason? Can you give any reason, or it is just "i don't like it"? :)