Application Service Layer – Calling Database Functions: Bad Architecture?

Architecturecode-qualitydesign-patternsmvc

Scenario:

  • Stack: Java, Spring, Hibernate.
  • Model: Client-Server Application.
  • Pattern: Model-View-Controller (MVC).

The Service Layer classes has three behaviors:

  1. Some services have the business rule within the methods and delegate the persistence to the application. Like:

    EntityManager.save(entity);

  2. Some services simply call a database function (passing parameters) Like:

    CallableStatement cls = con.prepareCall("{call databaseFunction(args)}");

  3. Some services have methods with both behaviors.

My questions:

  1. Is there any problem in having application services call – directly – database functions? Is not this considered bad practice? What would be an architecture model applicable to a project like this?
  2. Is there any problem in having the behavior mix in the same service? Such as transactions and consistency?
  3. In the case of maintenance, does this encapsulation make it obscure to the developer that he should also change the functions in the database? How to avoid this?
  4. Does this scenario happen in other applications around the world or was it just an architectural error?

Best Answer

Is there any problem in having application services call - directly - database functions? Is not this considered bad practice?

I think there is. You are placing a knowledge about the database internals to the application service. Changing database in any way (changing storage engine or even renaming a field or creating index) might require you to change application service and that violates SRP.

What would be an architecture model applicable to a project like this?

See comment below.

Is there any problem in having the behavior mix in the same service? Such as transactions and consistency?

I do not believe there is a technical problem, but there is a logical one. You just mix two approaches in the application making it vague, less structured, hard to adapt to changes. See comments above about violating SRP also.

In the case of maintenance, does this encapsulation make it obscure to the developer that he should also change the functions in the database?

Sure it does.

How to avoid this?

Place methods and functions, that directly work with database into a separate level of abstraction (be it a DAO layer or a simple repository pattern - depends on the complexity of your application)

Does this scenario happen in other applications around the world or was it just an architectural error?

I think in our world everything happens ;)