While I know that the use of Exceptions for control-flow is generally a bad idea, I can’t help but think of all the advantages that would come with it during the POST handling code in actions.
Take the typical scenario:
if (isset($_POST['Foo'])) {
$foo->setAttributes($_POST['Foo']);
if($foo->validate(){
if ($foo->save()) {
$messages['success'] = "notify user it was successfull"
} else {
$messages['error'] = "notify user of unexcepted error"
}
} else {
$messages['error'] = "notify user that his fields are invalid"
}
}
Reimagined with Exceptions, where ValidationException and SavingException extend the PostHandlerException:
if (isset($_POST['Foo'])) {
try{
$foo->setAttributes($_POST['Foo']);
if(!$foo->validate()){
throw new ValidationException(); // this has the msg alerting users to check the field
}
if(!$foo->save()){
throw new SavingException(); // this has the msg alerting users that something went wrong, and logs it
}
$messages['success'] = "notify user it was successfull"
}catch(PostHandlerException $e){
$messages['error'] = $e->getMessage();
}
}
This way, regular ("real") exceptions are still handled as before, but the code is more easily read (as you can see the consequences of a negative action directly, and not below X lines of code before the else statement), and easier maintained, it seems to me. It might not be clear from this trivial case, but it is not uncommon (in some of our production code) to have 3-4 levels of nested ifs before an action is finally handled (e.g., saved).
Or am I just delusional and this remains a a code smell ?