I'm currently working on a big file I have to parse and process and each step needs to be done in an order as I do SQL queries and need inserted IDs to make other insertions ... The problem is I often find my code to look like this :
if( function1() ) {
// process things to continue
if( function2() ) {
// process things to continue
// ... and so on
} else {
// fail2
}
} else {
// fail1
}
And same goes for form validations, etc... and it gets really hard to follow the steps, and it's just not pleasant to see in the code.
As I said, I need function1
to be done before function2
, so I can't do otherwise than be sure previous functions are done correctly.
Is there as proper way, or a design pattern, to code this kind of chained conditional functions ?
(FYI : I use OO PHP5, and I'm pretty much a novice in terms of standards in programming, so please don't behead me if this is casual !)
(concerning possible duplicate of When, if ever, should I daisy chain functions? ) : the functions can be used seperately and thus can't be used with daisy-chaining (see "B" in the given link).
The //Fail
s are here to "raise a flag" to say there has been a problem and further in the code (after the if/elses) it rollbacks all changes (with PDO's transaction rollback). But I would like to warn user there has been a problem, write a message (database error ? empty values ? ...) and maybe pass more informations like variables to be displayed/debugged.