I always see some classes that is named "ClassNameService", well what is the difference as logic? What is the goal of these service classes?
A service class is a named group of work within a workload with similar performance goals, resource requirements, or business importance. You must define at least one service class. You can define up to 100 service classes. Each service class must contain at least one performance period.
Services are used to fetch information from a data source (most likely a repository), process the information and return the result to the caller. A service class can use multiple repositories to achieve the wanted result.
Given any two objects that interact, the object making a method call is a client, and the object being invoked is the service.
Services are the building blocks. OOP = Objects are the merger of data and behavior. Objects are the building blocks. OOP languages need to have four features. First, the ability to create objects.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With