Web-development – Where to put business logic in MVC design

business-logicmvcobject-oriented-designweb-development

I have created a simple MVC Java application that adds records through data forms to a database.

My app collects data, it also validates it and stores it. This is because the data is being sourced online from different users. the data is mostly numeric in nature.

Now on the numeric data being stored into database (SQL server), I want my app to perform computations and display the results. The user is not interested in how computations are done so they must be encapsulated. The user must only be able to view the simple computed data (for example, A column data minus B Column data divided by C column data). I know how to write stored procedures for same but I want a three-tier app.

I want the data that I put into the database as a record, worked upon by performing calculations on it. The original data should remain unaffected, while the new data, post-calculations, must be stored as a new entity record into the database.

Where should I write the code for this background calculation? As it is the rules and business logic, should I put it in new JavaBeans files?

Best Answer

The business logic should be placed in the model, and we should be aiming for fat models and skinny controllers.

As a start point, we should start from the controller logic. For example: on update, your controller should direct your code to the method/service that delivers your changes to the model.

In the model, we may easily create helper/service classes where the application business rules or calculations can be validated.

A conceptual summary

  • The controller is for application logic. The logic which is specific to how your application wants to interact with the "domain of knowledge" it belongs.

  • The model is for logic that is independent of the application. This logic should be valid in all possible applications of the "domain of knowledge" it belongs.

  • Thus, it is logical to place all business rules in the model.