Last week I had a design talk with the software architect of my current project because of a code review we were performing for the offshore team. In order to encapsulate common methods to be used by a class, he wanted to use an Utility Class and I suggested to use a Service instead. I didn’t “win” the discussion because I’m not the architect and at the end the Helper/Utility class was said to be implemented, but I defended my point of view and I still think it would be the right approach, here I will explain why.
An Utility class is a class that performs common used functions generally with static methods, while a Service is a self-contained unit of functionality, consisting of an interface which contains the signature of the methods that the Service is going to expose and one or more implementation classes.
The argument he gave me for the Utility class was that a service was “too complex”. In my humble opinion, when you have an IoC Container, that is “bread for today and hunger for tomorrow”. I think it isn’t too complex (it is rather simple) to add an interface with the method’s signature and there are several benefits in counterpart, for example:
  1. Be able to easily switch the implementation of the service.
  2. Adherence to SOLID principles and in concrete to Dependency Inversion Principle from Robert C. Martin,
  3. Easy to test.
In other words: Decoupling -> good architecture/design principles.

Your business may need to be able to easily switch the implementation, with a service your code depends on interfaces, not on concrete implementations, which let you change your strategy “on the fly”. Following this approach we can start talking of the benefits of the Dependency Inversion, but this is such an important concept that I will left it for another post. I will end this post with the testability. If you are used to test with JUnit and Mockito, you will now, that if your code is follows good design principles, it will be very easy to test. But what happens if you start using static methods like for example in an Utility class? Mockito can’t handle that and you will need to use Powermock on top of it, as said, Mockito will challenge you to write your code with good principles… as I like to say: “If you can’t test it with Mockito, then you may refactor your code”.

And you? What is your opinion?