Search code examples
javadesign-patternsmulti-tier

Best practice for validating input data for multi-tier application


In our application we have various layers. Service Layer, DAO layer and actions (struts applications).

Data gets passed from one layer to another layer.

Where we should ideally put input validation ?

Say, userid, phone number is coming from UI, They are mandatory. So we are already doing validation at client side.

Now, As per my opinion, Thts all u need. No where else it should be validated.

But one of my colleague argues, what if client makes request directly. So we need to add in Actions also.

Now, At Dao as well, same method is getting used at some other action and tht does not have validation,

Or, Say service layer, It might be exposed as , say as web service, So there also u shd have validation.

So essentially, He is suggesting..we shd have validations everywhere. Which does not make sense for me. Its duplication across layer.

What is ideal approach for this ? Say validation is of may be simple null check or some complex validation.


Solution

  • Agree with Pangea, you should definitely have validations in the client and service endpoints.

    I would add that the concept of validations is to be "fail-fast". You add validations to each layer so that the user or caller would get immediate feedback as to why the call would fail instead of potentially starting a transaction, making complex queries and doing a write only to find that a field is too short.

    On the client-side, you want as much validation as possible so that you won't waste the user's time, bandwidth and server-side resources (which have contentions in many cases). However, you usually can't do all validations on the client-side (for example, to check for whether there is already such a username in use on signup) so you would want that checked and a proper error message returned as soon as you hit the service layer.

    On the server layer, you want to assume that all inputs are potentially dangerous and incorrect (and they often times will be). I actually think it's better to be more comprehensive and aggressive on validating inputs on the service layer since that's your last line of defense. If you leave out a validation or two on the client side, you just need a nice fault handling mechanism to let the users know what's wrong. If you miss something on the service side and disaster strikes, it could mean hours or days of debugging and trying to restore database backups.

    There are some checks that are done at the database level as well which enforce things like referential integrity and such. I usually try as much as possible to check for them before attempting a write since interpreting various RDBMS's error messages and trying to convert them back to user understandable lingo is often hard if not impossible.