1

I have a question. I have these classes:

public interface CRUDService<MODEL extends BaseModel<ID>,ID extends Serializable>
{
     List<MODEL> findAll();
     MODEL findById(ID id);
     // + delete, save & update methods
}

public abstract class AbstractCRUDService<MODEL extends BaseModel<ID>,ID extends Serializable> implements CRUDService<MODEL,ID>
{
     //overriding the CRUDService interface methods here.
}

Is it better to extend each service from AbstractCRUDService like this:

public class DefaultProductService extends AbstractCRUDService<ProductModel,Long> implements ProductService
{ //some methods here}

or should I remove abstract from AbstractCRUDService and inject this service in the DefaultProductService ?

public class DefaultProductService implements ProductService {
    @Autowired
    private CRUDService<ProductModel,Long> crudService;

    // override "ProductService" methods here.
}
user1234SI.
  • 1,812
  • 1
  • 8
  • 22

2 Answers2

0

It depends on your requirement.

If all Model Types, need the same CRUD implementation, you can go with your 2nd approach: composition.

However, if different Model objects require different CRUD implementations, the inheritance would fit better. For example, for all ProductModels Del(obj) will remove the object from the DB table, however, for all OrderModels Del(obj) doesn't remove the data, instead, it does something else, throw an exception, for example.

Kent
  • 189,393
  • 32
  • 233
  • 301
  • Oh, so when I need another implementation for `delete` method I simply override it in the main class in case of inheritance. – user1234SI. Jun 09 '20 at 10:02
0

Yes, it is. You need to prefer composition over inheritance

here a really good post to read about it

composition over inheritance

ozzem
  • 294
  • 1
  • 3
  • 16