Service Objects With Rails Using Aldous

One of the concepts we've had great success with in the Tuts+ team is service objects. We've used service objects to reduce coupling in our systems, make them more testable, and make important business logic more obvious to all the developers on the team. 

So when we decided to codify some of the concepts we've used in our Rails development into a Ruby gem (called Aldous), service objects were top of the list.

What I'd like to do today is give a quick rundown of service objects as we've implemented them in Aldous. Hopefully this will tell you most of the things you need to know in order to use Aldous service objects in your own projects.

The Anatomy of a Basic Service Object

Service
Photo by Dennis Skley

A service object is basically a method that is wrapped in an object. Sometimes a service object can contain several methods, but the simplest version is just a class with one method, e.g.:

We're all used to using nouns to name our objects, but sometimes it can be hard to find a good noun to represent a concept, whereas talking about it in terms of an action (or verb) is simple and natural. A service object is what we get when we 'go with the flow' and just turn the verb into an object.

Of course, given the above definition we can turn any action/method into a service object if we so desire. The following...

... could be turned into:

We could write several other posts about the effect service objects might have on the design of your system, the various trade-offs you'll be making, etc. For now let's just be aware of them as a concept and consider them just another tool we have in our arsenal.

Why Use Service Objects in Rails

As Rails apps get bigger, our models tend to become quite large, and so we look for ways to push some functionality out of them into 'helper' objects. But this is often easier said than done. Rails doesn't have a concept, in the model layer, which is more granular than a model. So you end up having to make a lot of judgement calls:

  • Do you create a PORO model or do you create a class in the lib folder?
  • What methods do you move into this class?
  • How do you sensibly name this class given the methods we've moved into it? 

You now need to communicate what you've done to the other developers on your team and to any new people who join later. And, of course, faced with a similar situation, other developers might make different judgement calls, leading to inconsistencies creeping in.

Service objects give us a concept which is more granular than a model. We can have a consistent location for all our services and you only ever move one method into a service. You name this class after the action/method that it will represent. We can extract functionality into more granular objects without too many judgement calls, which keeps the whole team on the same page, allowing us to get on with the business of building a great application. 

Using service objects reduces coupling between your Rails models, and the resultant services are highly reusable due to their small size/light footprint. 

Service objects are also highly testable, as they usually won't require as much test boilerplate as more heavyweight objects, and you only worry about testing the one method that the object contains. 

Both the service objects and their tests are easy to read/understand as they are highly cohesive (also a side-effect of their small size). You can also discard and rewrite both service objects and their tests almost at will, as the cost of doing so is relatively low and it is very easy to maintain their interface.

Service objects definitely have a lot going for them, especially when you introduce them into your Rails apps. 

Service Objects With Aldous

Aldous
Photo by Trevor Leyenhorst

Given that service objects are so simple, why do we even need a gem? Why not just create POROs, and then you don't need to worry about another dependency? 

You could definitely do that, and in fact we did this for quite a while in Tuts+, but through extensive usage we ended up developing a few patterns for services that made our lives just that little bit easier, and this is exactly what we've pushed into Aldous. These patterns are light and don't involve a lot of magic. They make our lives a tiny bit easier, but we retain all the control if we need it.

Where They Should Live

First things first, where should your services live? We tend to put them in app/services, so you need the following in your app/config/application.rb:

What They Should be Called

As I've mentioned above, we tend to name service objects after actions/verbs (e.g. CreateUser, RefundPurchase), but we also tend to append 'service' to all the class names (e.g. CreateUserService, RefundPurchaseService). This way no matter which context you're in (looking at the files on the file system, looking at a service class anywhere in the codebase) you always know you're dealing with a service object.

This is not enforced by the gem in any way, but worth taking into account as a lesson learned.

Service Objects Are Immutable

When we say immutable, we mean that after the object is initialized, its internal state will no longer change. This is really great since it makes it much simpler to reason about the state of each object as well as the system as a whole.

In order for the above to be true, the service object method can't change the state of the object, so any data must be returned as an output of the method. This is difficult to enforce directly, since an object will always have access to its own internal state. With Aldous we try to enforce it via convention and education, and the next two sections will show you how.

Representing Success and Failure

An Aldous service object must always return one of two types of objects:

  • Aldous::Service::Result::Success
  • Aldous::Service::Result::Failure

Here is an example:

Because we inherit from Aldous::Service, we can construct our return objects as Result::Success. Using those objects as return values allows us to do things like:

We could, in theory, just return true or false and get the same behaviour as we have above, but if we did that we couldn't carry any extra data with our return value, and we often want to carry data.

Using DTOs

The success or failure of an operation/service is only part of the story. Often we will have created some object which we want to return, or produced some errors of which we want to notify the calling code. This is why returning objects, as we've shown above, is useful. These objects are not just used to indicate success or failure, they are also data transfer objects.

Aldous allows you to override a method on the base service class, to specify a set of default values that objects returned from the service would contain, e.g.:

The hash keys contained in default_result_data will automatically become methods on the Result::Success and Result::Failure objects returned by the service. And if you supply a different value for one of the keys in that method, it will override the default. So in the case of the above class:

In effect the hash keys in the default_result_data method are a contract for the users of the service object. We guarantee that you would be able to call any key in that hash as a method on any result object that comes out of the service.

Error-Free APIs

Error Free
Image by Roberto Zingales

When we talk about error-free APIs we mean methods that never raise errors, but always return a value to indicate success or failure. I've written about error-free APIs before. Aldous services are error-free depending on how you call them. In the example above: 

This will never raise an error. Internally Aldous wraps your perform method in a rescue block and if your code raises an error it will return a Result::Failure with the default_result_data as data. 

This is quite liberating, because you no longer have to think about what can go wrong with the code you've written. You're only interested in the success or failure of your service, and any error will result in a failure. 

This is great for most situations. But sometimes, you want an error generated. The best example of this is when you're using a service object in a background worker and an error would cause the background worker to retry. This is why an Aldous service also magically gets a perform! method and allows you to override another method from the base class. Here is our example again:

As you can see, we've now overridden the raisable_error method. We sometimes want an error to be produced, but we also don't want it to be any type of error. Otherwise our calling code would have to become aware of every possible error that the service can produce, or be forced to catch one of the base error types. This is why when you use the perform! method, Aldous will still catch all the errors for you, but will then re-raise the raisable_error you've specified and set the original error as the cause. You could now have this:

Testing Aldous Service Objects

You may have noticed the factory method usage:

You should always be using these, and never construct service objects directly. The factory methods are what allow us to cleanly hook in the nice features like automatic rescue and adding the default_result_data.

However, when it comes to tests, you don't want to have to worry about how Aldous augments the functionality of your service objects. So, when testing, simply construct the objects directly using the constructor and then test your functionality. You'll get specs for the logic you wrote and trust that Aldous will do what it's supposed to do (Aldous has tests of its own for this) when it comes to production.

Conclusion

Hopefully this has given you an idea of how service objects (and especially Aldous service objects) can be a nice tool in your arsenal when working with Ruby/Rails. Give Aldous a try and let us know what you think. Also feel free to have a look at the Aldous code. We didn't just write it to be useful, but also to be readable and easy to understand/modify.

Tags:

Comments

Related Articles