Method chaining vs encapsulation

Posted by Oak on Programmers See other posts from Programmers or by Oak
Published on 2011-02-16T09:24:09Z Indexed on 2011/02/16 15:33 UTC
Read the original article Hit count: 264

Filed under:
|

There is the classic OOP problem of method chaining vs "single-access-point" methods:

main.getA().getB().getC().transmogrify(x, y)

vs

main.getA().transmogrifyMyC(x, y)

The first seems to have the advantage that each class is only responsible for a smaller set of operations, and makes everything a lot more modular - adding a method to C doesn't require any effort in A, B or C to expose it.

The downside, of course, is weaker encapsulation, which the second code solves. Now A has control of every method that passes through it, and can delegate it to its fields if it wants to.

I realize there's no single solution and it of course depends on context, but I would really like to hear some input about other important differences between the two styles, and under what circumstances should I prefer either of them - because right now, when I try to design some code, I feel like I'm just not using the arguments to decide one way or the other.

© Programmers or respective owner

Related posts about oop

Related posts about encapsulation