This falls straight into the same category with the recent "Is it better practice to return if false or execute an if statement if true?" question.
Often, while writing code, I find myself presented with two options. Either I can do this:
public void myMethod() throws Exception {
// Some code
validate(some_object_or_condition);
// Some code
}
private void validate(Object arg) throws Exception {
// Code that validates the argument and throws an exception if it's invalid
}
Or this:
public void myMethod() throws Exception {
// Some code
if( !isValid(some_object_or_condition) ) throw new Exception();
// Some code
}
private boolean isValid(Object arg) {
// Code that returns a boolean based on whether or not the argument is valid
}
Is either one preferable over the other? When I was still just learning Java the latter felt more "object oriented" and somehow more natural. However, with experience the former has started to feel better because then the code looks cleaner to me, but I'm afraid people might find it less readable.
Edit/Add: This time I ran into this problem when implementing a game (just for the fun of it) where the user would place words into a grid. The playWord
method may fail because of the word not actually being a real word (yielding an InvalidWordException) or because the user is trying to place a valid word into an illegal position (yielding a WordPlacementException). If the method does not fail, it should return the score of the word as an integer. So in my case the playWord method first calls the method that validates the word and later the method that validates the location of the word, and these provoked this question here.