Let’s say I have a function that looks like this:
public void saveBooking(/* some inputs */) {
//save into database
}
Before saving into database, I have to do various validations. What I can do in my main program is like this:
//do all the validations and do any necessary handling. Then...
saveBooking(/*inputs*/);
With this, I’m sure that all the data have to pass all the validations required before saving into database. However, this means that the function saveBooking() closely depends on the validation methods. Every time I want to call saveBooking(), I have to make sure that I don’t forget to call the validations.
Alternatively, I can put all the validations inside the function itself so that all I should do is to call the method and everything is taken care of. However, in order to handle all the errors independently, I have to do make the function throw exceptions and catch in the main program. It should look something like this:
public void saveBooking(/* some inputs */) /* throws various exceptions */ {
//various validations
//save into database
}
//...and in the main program...
try{
saveBooking(/*inputs*/);
}
catch(MyException1 e1){
//do something
}
catch(MyException2 e2){
//do something
}
This also means I have to create multiple exceptions on my own. The good thing is I don’t have to worry what validations I have to put before hand.
With these, I’m not sure which one is the best code design. I personally prefer the first method which is more readable but it depends on each other too much and it’s getting worse when I need to use it in many places.
Definitely the first option over the second. I consider the second to be an abuse of exceptions. Exceptions are meant for exceptional circumstances, and failing validation is not “exceptional.”
Put the validation logic into a separate method, and have
saveBooking()call the validation method before it does anything else.