Message Chain — Code Smells Catalog Skip to content

Message Chain

Data Dealers Message Calls Code SmellDesign Smell Between Class

object.getA().getB().getC().getD() — the caller knows the entire relationship chain, and every intermediate link becomes a dependency that breaks when any relationship changes.

2 min read 1 source

Overview

Suppose that class A requires data from class D, but to retrieve those data, it has to make unnecessary calls to class B sequentially and then C to get it. This function sequencing is called Message Chain code smell. Long sequences of methods calls indicate hidden dependencies by being intermediaries. A sequence of temporary variables could have also hidden the sequence of methods. The problem with this smell is that any change in the intermediate relationship causes the client to have to change. [1]

Causation

Classes ask the objects to do the manipulation instead of telling the object with which manipulation should be done.

Problems

Law of Demeter Principle Violation

Law of Demeter specifies that each class should have limited knowledge about other classes and only to these classes, which are "closely" related to the current class.

Tell, Don’t Ask Principle Violation

The manipulation should be done by telling the object to manipulate, not by asking for permission to manipulate.

Example

1class Minion:
2    _location: Location
3
4    def action(self):
5        ...
6        if self._location.field.is_frontline():
7            ...
8
9class Location:
10    field: Field
11
12class Field:
13    def is_frontline(self)
14        ...
PYTHON

Exceptions

In the context of the system as a whole, some communication between modules must take place. All possibilities should be properly balanced so that none of the smells dominate (Global Data, Tramp Data, Message Chain, Middle Man) to make the entire codebase as straightforward as possible.

Refactoring

  • Hide Delegate
  • Extract Method
  • Move Method

Sources

Browse All 56 Smells