3

I am using Spring framework usually with the common simple form:

Controller <-> Service <-> Repository

And I usually have a common services that I put inside a CommonService class and make all other serivces extends class.

A developer told me that it is better to inject the CommonClass in each service instead of using inheritance.

My question, Is there one approch better than the other? Do JVM or performance affected by one more than the other?

Update

There is no direct relationship between CommonService and other Services, it is not has-a or is-a relationship, it's like a utility service.

Ebraheem Alrabeea
  • 2,130
  • 3
  • 23
  • 42

1 Answers1

3

It is the principle of favoring composition over inheritance. If you inherit from a certain class, both are tightly coupled which makes it harder to keep separate things separate.

Unless an there is an is-entity relationship between the two, it is better to model a uses-entity relationship, because this allows for easier changes later on.

Of course it depends on the use case and it is more of a design and architecture question than a performance aspect.

ldz
  • 2,217
  • 16
  • 21
  • 1
    Here's an example of the [related discussion](https://www.thoughtworks.com/de/insights/blog/composition-vs-inheritance-how-choose) – Curiosa Globunznik Dec 09 '19 at 11:06
  • 1
    There is the `is-a` relation though. Every `Service` in question `is-a CommonService`, and if it is said that every `CommonService` depends on `X`, `Y` and `Z` to do `A`, `B` and `C`, I see no benefit in extracting `X`, `Y`, and `Z` into a separate injectable just to get rid of inheritance. – M. Prokhorov Dec 09 '19 at 11:20
  • @M.Prokhorov, yes it is exactly as you said, so in the end it is return to the developer to decide what is the better, that what I understand so far, I will continue with using Inheritance :) – Ebraheem Alrabeea Dec 09 '19 at 11:26
  • @EbraheemAlrabee', there might be a point to his suggestion if everything a `CommonService` needed for is an implementation detail of individual services. I.e. if `CommonService` has no public API. – M. Prokhorov Dec 09 '19 at 11:29
  • `CommonSerivce` has no public API, it is just an implemented methods uses diffrent repositories that do one task, and other method that work after user submit to an API (Ex. extracting some data from the request header). – Ebraheem Alrabeea Dec 09 '19 at 11:39
  • You can say there is no direct relationship between `CommonService` and other Services. – Ebraheem Alrabeea Dec 09 '19 at 11:41