Video in progress

Strong Middle 🧱 OOP and SOLID

What problems does a common `AbstractCrudService<T, ID>` base class for all services lead to?

At first duplication drops, but then every service starts overriding parent methods to add its own rules, and the base class bloats with flags and hooks. The same CRUD API gets exposed for every entity, even for ones that must never be deleted.

📖 Answer

The usual start:

public abstract class AbstractCrudService<T, ID> {
    protected abstract JpaRepository<T, ID> repo();
    public T get(ID id) { return repo().findById(id).orElseThrow(); }
    public T save(T e) { return repo().save(e); }
    public void delete(ID id) { repo().deleteById(id); }
    public Page<T> list(Pageable p) { return repo().findAll(p); }
}

class InvoiceService extends AbstractCrudService<Invoice, Long> { ... }

A year later:

  • delete is forbidden for InvoiceService, so it overrides it and throws an exception (LSP broken);
  • some services need an audit on save, others need an event, so beforeSave()/afterSave() hooks get added to the base class, and then a boolean skipAudit flag;
  • list now has to filter by tenant, so either all the children break or each one overrides it;
  • if the controller is also an AbstractCrudController, the DELETE /invoices/{id} endpoint has been opened "for free".

The core mistake is that a shared technical shape (CRUD) was taken for shared behavior. In reality, the rules of Invoice, User and Course are completely different.

What I do:

  • each service declares its own domain operations: issue(), cancel(), markPaid(), not a generic save();
  • the truly shared technical part (paging, error mapping, audit) goes in through composition: a helper component or an aspect;
  • Spring Data repositories are already generic, so building another generic layer on top of them is often overkill.

Where the CRUD really is uniform, like an admin panel, the generic approach is fine. Just keep it separate from the domain module.