Method Chaining vs Encapsulation – Object-Oriented Design

encapsulationobject-oriented

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.

Best Answer

I think the Law of Demeter provides an important guideline in this (with its advantages and disadvantages, which, as usual, should be measured on a per case basis).

The advantage of following the Law of Demeter is that the resulting software tends to be more maintainable and adaptable. Since objects are less dependent on the internal structure of other objects, object containers can be changed without reworking their callers.

A disadvantage of the Law of Demeter is that it sometimes requires writing a large number of small "wrapper" methods to propagate method calls to the components. Furthermore, a class's interface can become bulky as it hosts methods for contained classes, resulting in a class without a cohesive interface. But this might also be a sign of bad OO design.

Related Topic