Make Your Service Object Stateless

Valera Prokopchuk
Hired Engineering
Published in
2 min readJul 26, 2019

Sometimes it might be tempting to create a Service Object that returns several results at once and exposes those results as attributes:

Or there might be a different manifestation of the same approach — exposing an execution error as an attribute of the Service Object:

Both approaches have one important thing in common: in both cases, the service object instance changes its state after execution so it might be fair to call such service objects stateful.

There are several disadvantages of Service Objects that change their state:

  1. One can not use such Service Objects without carefully examining their internals and understanding how they can be consumed and what attributes are updated
  2. Such Service Objects are particularly difficult to refactor. The whole codebase must be scanned and all places where an error attribute must be checked if a new error attribute is added (for example if its meaning is changed).
  3. It might be not obvious sometimes whether the Service Objects are executed and if their attributes are ready:

So — what can be done to avoid such stateful service objects?

  1. Reconsider your Service Object one more time if you feel the need to return several results from it. There is a chance that your Service Object violates the Single Responsibility Principle and should be split into several Service Objects:

This is the best that can be done to any Service Object — split it and simplify each part.

2. If you still believe that the service does not violate the Single Responsibility Principle and still need several results from it then consider introducing a special result object:

Using a custom result class will allow you to add a behavior to it (validation for example), to change the implementation of its attributes and all that without messing up the original Service Object code.

3. Use a custom exception class instead of error attributes:

Using exceptions makes the code safer. The error is guaranteed when something wrong happened. And it is very important to get an error as early as possible.

--

--