Anti-Patterns and Worst Practices – Monster Objects

monster Monster objects (or God objects) know too much, or do too much; monster objects are nasty beasts. The term God object was coined because these objects are said to be “all-knowing”. I’m in favor of the term Monster objects because knowing something isn’t a bad thing. These objects are usually bad things and Monsters are both big and bad, I find that more fitting. There are several problems with this anti-pattern. The two problems I most often see are testability problems and violating the Law(Suggestion) of Demeter.

Defensive Coding

I try to do my best when adding new functionality to avoid creating a monster object by continually asking myself if this new code is going to add an “and” to this class. If you’re tacking on code that makes the class do this “and” that, you’re probably adding it in the wrong spot. If this continues, you’re headed in the wrong direction. This is the primary tenet of the Single Responsibility Principle.

Violating Law of Demeter


You know you’re dealing with one of these when you find yourself burrowing down the member/function chain like the following:


Likely your tests include creating a lot of setup code:

var price = new Money(35m);
var pricing = new Pricing() { MembershipPrice = price };
var product = new Product() { Pricing = pricing };
var orderItem = new OrderItem(product);

Instead, you probably want to break this apart if possible. There’s no benefit in having the OrderItem ask the Product to have its Pricing… you get the point.

For this example, you could likely remove the Pricing class entirely by incorporating some patterns here. The strategy pattern is a good one to follow when you need to run some calculations given a specific set of criteria.

var calculatedPrice = orderItem.CalculatePrice(new MembershipPricingStrategy()); 

Dealing With Monsters

A good way to deal with monster objects is to not deal with them. If you’re stuck with one for a while, abstract out what need from it and use the abstraction. Wrap this functionality in some code that you own (or are more free to modify) like Colin does in Breaking Free from HttpContext.

Monster Objects in the Wild

Lately, whenever I think of this anti-pattern, ASP.Net MVC’s HttpContextBase comes to mind. What other objects have you encountered that are “monsters”?

[See more Anti-Patterns and Worst Practices]

Anti-Patterns and Worst Practices – The Arrowhead Anti-Pattern