Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Inheritance vs Dependancy Injection "Autowired" [closed]

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.

like image 919
Ebraheem Alrabeea Avatar asked Feb 26 '26 03:02

Ebraheem Alrabeea


1 Answers

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.

like image 143
ldz Avatar answered Feb 27 '26 15:02

ldz