Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid duplicate validation in web tier and service tier?

If I have a web app, say I'm using Spring MVC, and I add validation in my forms and controllers. I might also have validation in my service tier in case clients access my app in some other manner (through a REST service, etc). In this case I'm likely to have validation logic/code in multiple places.

Is there a suggested approach to keep the validation portion DRY?

like image 355
codecraig Avatar asked Dec 29 '22 02:12

codecraig


1 Answers

Lots of people will tell you how to do this. I'm going to answer with why you might not want to.

In an N-tier system, the tiers all operate semi-autonomously. But that doesn't mean they can - or should - rely on another tier to guarantee data consistency and validity.

There are two major reasons. First, an N-tier system is expandable. For example, in a web system a new front end might take advantage of an existing web tier to do something never thought of in the original design. So you are design proofing your system by allowing for something new to come at some middle point in the tiers.

Second, validation is often most effective the closer it is to the user. If I'm in a browser based solution and I type in the wrong password in a double-enter validation field, I would like the browser to point that out immediately. Waiting for the round trip takes time and frustrate the user.

Now take that same example and move it to the logic tier. The logic tier, not exactly sure who is sending it data, wants to make certain that it is receiving two matching passwords. So it also checks, and returns an error if they don't match. This protects the data from bad changes.

It's just a philosophy, but it has worked well for me in the past.

like image 63
Jonathan B Avatar answered Jan 13 '23 13:01

Jonathan B