logic

Where Should This Logic Live?

I have noticed developer confusion around when we should place logic in the Frontend or the Backend of a modern client-server application. 

These days, the Frontend (FE) are mobile and web apps. The Backend (BE) comprises a web-based API encapsulating the business rules. In a modern client-server web-based system, the FE clients send requests to the API, and the API responds appropriately. One request might ask for a customer’s orders, while another saves a user’s preferences.

So, what is the confusion?

Say, we have a typical web-based client-server system. A frontend made up of a mobile app and a web app. The backend is a REST API.   

Now, let’s assume that the web app calculates and applies the sale tax, not the API. Our company first developed the web app—the mobile app is a recent addition. When a developer wrote the mobile app, they copied the web app’s sales tax calculations into the mobile code. 

The sales tax calculations are in the FE:

Six months later, legislators in our state increase sales tax from 10% to 15%. We implement the changes in the mobile app but forget to make the change in the web app! 

Customers don’t pay the full tax amount. Our company must make up the shortfall to the taxman. We quickly fix the problem in the web app. Once again, all clients calculated sales tax at the new, higher rate.

However, this debacle lost the company a lot of money. Programmers are in the dog-box with management for months.

The problem with putting common logic in the frontend is that:

  1. It must be correctly replicated in each client, and then
  2. It must be kept in sync between clients.

Is there a better way?

Yes. We could have put the sales tax calculations into the Backend API. Common business logic, such as sales tax calculations, should go there. 

Let’s assume we had the original sales tax calculations in the BE:

As shown, the 10% sales tax calculations express themselves across both clients.

When the sales tax increases to 15%, we alter the backend code:

The updated sales tax calculations will immediately manifest themselves at the 15% rate across all the clients! The BE is a more appropriate place to keep common sales tax logic. 

As a rule, anytime we must have the same logic in two (or more) places is fragile and prone to failure. 

In general

  • Common logic belongs in the backend. E.g. sales tax calculations.
  • Logic unique to a client type belongs in the frontend. E.g. mobile app colour scheme. 
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply