0

I was wondering if it's an accepted way to call methods of classes within methods of classes within method of classes in Java like a cascade?

For example: Class_1 calls method from Class_2 and Class_2 calls a method from Class_3 and so on...

Or is this better: Class_1 calls method from Class_2. The return value is used to work with a method from Class_3 and so on... (-> one class handling all the method calls)

Another example: A class iterating over directories passing a value (like a file path) to a another class' method reading a specific file. Then again this class passes a value (like a line from the file) to a another class' method that analyses it. And then this class passes the result to another class' method again doing some other stuff with it.

Or is this better: A class calls a method that iterates over a directory. The return value (file path) is passed to another class' method called by the first class...

EDIT: Thanks for the answers!

cmtjk
  • 359
  • 2
  • 12
  • 2
    What you are referring to is called [`The Law of Demeter`](http://en.wikipedia.org/wiki/Law_of_Demeter). And it is bad form to break that law for all the reasons listed in that article. –  Apr 24 '15 at 16:00
  • 2
    You can do it either way. If you want to avoid the law of demeter in the first example, you can pass it a call back or lambda for it to call when it has a result. If you only have exactly one result is is likely to be over kill and the second example might be simpler. Note: if you can have one or more results, passing a lambda might be better. – Peter Lawrey Apr 24 '15 at 16:02
  • 1
    [Here is another duplicate about the Law of Demeter.](http://stackoverflow.com/questions/163071/coupling-cohesion-and-the-law-of-demeter?rq=1) –  Apr 24 '15 at 16:02
  • 1
    And as Peter states, *you can do it either way*, laws are meant to be bent sometimes ... it is a matter of personal opinion and experience in the end. That said, you break this law constantly and your code is guaranteed to become a *big ball of mud* sooner than later. Breaking this law is a entropy multiplier for sure! –  Apr 24 '15 at 16:03
  • 1
    note: if your stack depth is in the thousands you will see problems such as a Stackoverflow in extreme case, but also a truncated stack trace (the default limit is 1000) In real programs you can get horribly nested stack traces (web service libraries tend to do this) and it can look overly complicated. So while in your case, it is simple enough that it probably doesn't matter, you do want to avoid a very deep stack traces. IMHO. – Peter Lawrey Apr 24 '15 at 16:08

0 Answers0