Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use a service layer instead of a helper class for spring controllers?

In my experience this is how ive seen spring controllers used : Define a spring controller which returns a value of some type to presentation layer. The controller request mapping method calls a service layer. The service layer itself consists of an interface and implementation. The service interface always contains just one method so its not really polymorphic as it keeps 'one form' consistently. The service implementation may access data of some kind, perhaps from a DAO and returns it the controller. The controller may amend this data slightly before returning its returned to the presentation layer.

What is this point of having an interface in this case ? Ive never encountered a spring service implementation called from multiple controllers, so why the interface ?

Does it not make more sense to use a helper controller class which performs the actions of the service implementation ?

like image 334
blue-sky Avatar asked Dec 04 '25 13:12

blue-sky


2 Answers

Using Service layer is beneficial because it allows good logical separation of business logic from controller tasks. In Service class you can encapsulate business logic related to certain aspect like PaymentService. In PaymentService you can implement various methods like cardPayment(), paypalPayment(), refund(). Different controllers will be using the one single service. Moreover, service layer is also convenient for code reuse.

Using interfaces is convenient if you decide later to use some AOP features, add some logic (logging for example), in between of controller and service without changing it's code.

like image 67
Alexey A. Avatar answered Dec 07 '25 03:12

Alexey A.


You're right - a service interface tends to be use-case specific, however there are still a few good reasons to create an interface:

  • Its just good practice. Eg it allows swapping in a new implementation of the service. There's really no cost or negative impact to extract an interface via the IDE.
  • Allows the use of DynamicProxies for transaction management, security concerns etc. Dynamic proxies are faster than cglib proxies, and they don't require a default constructor. . . Also, in the past, proxies on concrete objects could sometimes be flaky, but DynamicProxies are so simple there's little room for something to go wrong.
  • As Luke Taylor mentioned, it simplifies testing.
like image 41
Jasper Blues Avatar answered Dec 07 '25 04:12

Jasper Blues



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!