There are two code snippets:
someObject.getBla1().getBla2().performBlah();
And the second one:
bla1=someObject.getBla1();
bla2=bla1.getBla2();
bla2.performBlah();
I am always told to avoid the first one, and use the second one, where as I feel that The second one is just a pain.
What’s the benefit in the second one?
Avoid both forms. The law of demeter is an important guideline when writing software that states
You’re violating this law because
someObjectknows thatbla2has aperformBlahmethod. If it really does need to have this kind of method them move it tosomeObjectand hidebla1andbla2from the outside world.someObject.getBla1().getBla2().performBlah()would then becomesomeObject.performBlah()and the internal implementation ofsomeObject.performBlahwould probably delegate tobla1which in turn would delegate tobla2to get the implementation. The important thing is to make sure that each object only knows its immediate friends and doesn’t reach out into the wider world (e.g.someObjectonly knows aboutbla1,bla1only knows aboutbla2).