Methods shouldn’t depend on prior method calls.

You want your code to be more loosely coupled, so it doesn’t break later.

If you make two method calls on an object and the second call depends on the first call, then the first call should return a different class of object.

Why? Well if both calls worked on the same class, and you removed the first call, the code would break.


In this example, the addPostage method requires that the addShippingAddress method has been called. If you call addPostage without having a shipping address, it will fail. Yet, both of these are methods on box.

This might not seem like a big deal, but imagine if a lot of logic gets inserted in between the two methods. Then down the road as the code is being altered, the addShippingAddress method falls into a if/else tree and a case occurs where it doesn’t get called. It’s not hard to image the code getting to a state where the failure can occur, and it would take a while to track down the problem.

addressedBox = box.addShippingAddress(order)
stampedBox = addressedBox.addPostage

Now addPostage is only called on an addressedBox. The method won’t exist on a normal box. If you refactor the code and come to an error here, it will be because you don’t have the object you need. “addressedBox not found” or “no such method addPostage”. This makes it a lot more obvious what needs to be done.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: