I always see some classes that is named "ClassNameService", well what is the difference as logic? What is the goal of these service classes?
-
5A Service class is used by a client to interact with some functionality in your application. Usually it is public, and has some business meaning. For example, a TicketingService class might allow you to buyTicket, sellTicket and so on. – Rahul Tripathi Apr 18 '15 at 09:06
1 Answers
Generally speaking, there could be a hierarchy of domain objects, which are controlled by the services. If these domain objects are only data placeholders, with no behavior, then this is not true to object-oriented programming.
What we have here is what Martin Fowler would call the Anemic Domain Model.
More commonly, within OOP, a group of domain objects have behavior whose interactions form business logic. This logic, in turn, is encapsulated by the Service.
Such services are stateful, with their state being comprised of these domain objects. Services may also be stateless and offer self-sufficient functionality.
Imagine, if you will, a very simple calculator API.
A HTTP request is sent to your application, which then uses the API to perform data extraction and some complex calculation. The application endpoint then returns a HTTP response containing the computed data as a SOAP/REST/etc. message.
Once the response is received, this should then be returned to the client that sent the original request.
You don't want to force your client to manually invoke the computation and transformation of the input. Instead, you want to simply offer them a service API which encapsulates this logic and returns to them the expected result.
For Spring applications, you have the Spring annotation @Service
.
-
-
8"If these domain objects are only data placeholders then this is not true to Object oriented programming." correction - it's not about "true" oop, it's about Domain Driven Development. Service has many definitions in many approaches, in particular, your example would be Eric Evan's definition of Service. And Anemic Domain Model is just an opinion of Martif Fowler (who is a friend of Evans). – drakonli Sep 16 '16 at 18:16