Validation - Throw Exceptions Early

Jakob Jenkov
Last update: 2014-06-23

When receiving input that needs to be validated before it can be used, validate all input before using any of it. You should not change any state in the application or attached systems until all input data has been validated. That way you avoid leaving the application in a half valid state.

For instance, in a DAO method that inserts a user and an address into two different tables in a database, do like this:

  check if user already exists
  validate user
  validate address

  insert user
  insert address

Do not do like this:


  check if user already exists
  validate user
  insert user

  validate address
  insert address

If you do like this, and the address turns out to be invalid you will still have inserted the user in the system. What happens when the user corrects the address and retry registering? He will be told that his user already exists, right?

The problem is not only related to database insertions. In general, validate all input before using any of it, to avoid leaving the application in a half valid (=unknown) state.

Jakob Jenkov

Featured Videos

Java Generics

Java ForkJoinPool

P2P Networks Introduction



















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next