Train Wreck

The train wreck anti pattern occurs when a series of method calls are appended to one another all in one line of code. If you find yourself spending a lot of time reading through a series of method calls and trying to figure out what the line of code is actually doing, you probably are dealing with a train wreck.

Example:

 client.GetMortgage().PaymentCollection().GetNextPayment().ApplyPayment(300.00)

Analysis:

This style of coding surfaces all objects on one line of code and leads to readability and maintainability issues. In the above line of code it is unreasonable to have the consumer understand all 4 objects at the same time when we can represent this simply as one method call on the object we are directly interacting with. We should strive to minimize unnecessary interactions with objects and keep the calls to a minimum to minimize complexity. This line of code is also not reusable with in the code base which leads to duplicate code if we wanted to perform this same function elsewhere in the code.

Solution:

Create a method which represents the desired behavior and tells the client what to do. This follows the "tell, don't ask" principle.

 client.ApplyMortgagePayment(300.00)

This allows the caller to only interact with one object at a time and will minimize having to know about all of the objects down the dependency tree. Also if we wanted to perform this same function elsewhere in the code it is completely resuable without any code duplication.


The fluent-calling style exploits syntactically similar dot-chains. In a fluent call chain, each "train car" method usually returns this (or a wrapped this as in DecoratorPattern, or a modified copy of this), and optionally the "caboose" consumes the final resulting object. Perhaps this is the exception that proves the rule?


See also LawOfDemeter.


EditText of this page (last edited November 10, 2014) or FindPage with title or text search