Service objects (no more fat model, skinny controller)

It seems that the fat model / skinny controller paradigm has ran it’s coarse.  These days developers are opting to factor code narrower with special purpose classes.  These are commonly called service objects.  The classes are more numerous, and the service objects are all single purpose – but what does that actually mean?

Why service objects?

The main function of a service object is to hold a very narrow bit of logic.  A better way to understand this is to think of the quote by Robert Cecil Martin:

“A class should have only one reason to change.”

Instead of creating many, many methods on just a small number of object as would normally be done in the ‘fat model’ style, the service object can actually be a specific instance of a class to handle the same logic.  The end result of the service object style is many more SINGLE PURPOSE classes.

Why do single purpose service objects matter?

One of the main benefits of utilizing service objects is that the classic rails approach of making another method for the nearest active record object can be done away with.  This leaves the code cleaner, more organized, and easier to test and modify business logic.

What about modules?

One question posed quickly concerns modules.  Modules can be mixed into classes and seem to serve some of the same functions as service objects.  Modules, however, can bloat the classes when mixed in and fall victim to some of the same problems as the ‘fat model / skinny controller’ approach.  Modules can also create very complex dependencies between the mixin and the model’s internals.

Something to think about.

When going over classes and models see if it wold be beneficial to create more single purpose service objects.  The initial hesitation will soon be replaced by relief when the flexibility of organization, ease of testing, and speediness of modification become apparent.


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 )

Google+ photo

You are commenting using your Google+ 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