I try to avoid else clauses whenever possible. My reason for doing so is, it forces me to write all conditions, required to process the data, at the beginning of each function. It's easier for me, to have all requirements visible at one place. Below them, I can describe pure how to process business data, without the need to check again for something being what I expect it to be.
function doSomethingAwesome(environment, input) {
if(environment !== 'secure') {throw new Error('Bad environment!'')}
if(input == undefined) {throw new Error('No Input given!')}
// do something with input based on environment
}
I see developers doing redundant checks just because they overuse 'else' everywhere. Or developers tend to nest everything regardless of their error handlings in any 'else' clause.
public boolean isSomethingAwesome(EnvironmentObj env, InputObj inp) {
if (EnvironmentObj != Null && EnvironmentObj.secure()) {
if (InputObj != Null && InputeObj.data() != Null) {
// do something with input based on environment
} else {
throw new Exception("Something's wrong with Input!");
}
} else {
throw new Exception("Something's wrong in Environment!");
}
}
The 'else' clause should be used for branching of data processing steps exclusively. Not for putting your 'throws' and 'return's in there.
Jan Vladimir Mostert
Idea Incubator