OOP – Are Service Objects Necessary in Object-Oriented Programming?

Architectureencapsulationobject-orientedobject-oriented-designseparation-of-concerns

I have been using AngularJs since a long time. Me and my team makes heavy use of services for retrieving the remote resources like Users which intern uses $http service so, basically, for each entity, I have services which fetches/stores etc that entity.

I was thinking why not the entity itself should be able to do that and services should be totally removed. I don't know if I am going in that direction but I need to know the opinion of others.

Best Answer

Extensive use of "service" is indicative of bad OOP. However, the nature of development sometimes make service-like classes unavoidable, such as in your case.

Your user entity should not be responsible for storing or retrieving itself; storing itself does not violate OOP, however, it violates many good architectural practices such as separation of concerns and the single responsibility principal. Allowing an object to store and retrieve it self will make your application very brittle, and hard to maintain.

You will need storage and retrieval service; however, simply labeling it a service is somewhat lazy imo. OOP is about nouns that verb; let's make this service a little more OOP...

An object that is responsible for only CRUD is called a repository. It should not contain anything other than CRUD methods. If you find your repository having a method like GiveUserPermission you are violating the repository pattern, it does not belong there; it either belongs in the User class or a mediator class of User and Permission. Each entity should have its own repository. A repository should not be responsible for multiple entities. And remember, it is per entity, not per table.

It is irrelevant whether your repository gets its data from a database or a http rest call; the rest of your application should be ignorant to this detail.