Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a best practice to use inheritance in the spring service layer?

I have two service beans called PowerUserManager and SimpleUserManager. Both @Service annotated classes have about 20% of the code in common.

I've built an inheritance tree with a common abstract class (BaseUserManager) to reduce redundancy between the two classes.

                               BaseUserManager
                                      |
                               ---------------
                               |             |
                       PowerUserManager  SimpleUserManager

Then in my @Controller or whatever client class, I use the @Autowired annotation to inject both PowerUserManager and SimpleUserManager and I use one of them depending on the instance of the User I'm dealing with.

I'm not comfortable using inheritance to factorize code especially in the service layer. Do you Spring fellows see a better way to do this ?

like image 568
webpat Avatar asked Oct 22 '22 16:10

webpat


1 Answers

You should ask yourself some fundamental questions before considering inheritance over composition in this case, and in general:

  1. Are all user managers a BaseUserManager? Is this a IS-A relationship in any possible case?
  2. Does it make sense to expose BaseUserManager public API everywhere where a user manager is invloved?
  3. Does BaseUserManager have a single responsibility?

If the answer is yes, then inheritance is the right way to go. Otherwise, you should probably redesign into several smaller components and treat PowerUserManager and SimpleUserManager as service facades.

like image 147
Szymon Jednac Avatar answered Oct 24 '22 09:10

Szymon Jednac