Introduction



if ( $conditionToPerform ) {

perform ();

} else {

return false ;

}





if (! $conditionToPerform ) {

return false ;

}

perform ();





function setPassword ( $password , $oldPassword ) {

if ( $password === $oldPassword ) {

return;

}

if (! $this -> checkPassword ( $oldPassword )) {

throw new Exception ( 'Wrong password.' );

}

if ( strlen ( $password ) < 8 ) {

throw new Exception ( 'Password too short.' );

}

if (empty( $password )) {

throw new Exception ( 'Empty password not permitted.' );

}

$this -> password = $password ;

$this -> save ();

}





function setPassword ( $password , $oldPassword ) {

if ( $password !== $oldPassword ) {

if ( $this -> checkPassword ( $oldPassword )) {

if ( strlen ( $password ) >= 8 ) {

if (!empty( $password )) {

$this -> password = $password ;

$this -> save ();

} else {

throw new Exception ( 'Empty password not permitted.' );

}

} else {

throw new Exception ( 'Password too short.' );

}

} else {

throw new Exception ( 'Wrong password.' );

}

}

}



it is easier to read

reordering conditions is easier because they are not nested

the link between a condition and the corresponding Exception is more obvious

keep the indentation lower, which makes life easier with the limit of 80 chars/line

less line are changed across revisions which decrease the number of SVN conflicts possible and easier the code review. Take a look at the following pictures showing the same change requests (doing nothing if old and new password are the same + checking that password contains 8+ chars) implemented with the two styles:



Using "Return as soon as possible"™ Using "Return as soon as possible"™





Using nested conditions Using nested conditions

This is the first article of a series I will dedicate to tips to write PHP code that is easier to maintain, review, refactor,... These tips may be applied for other languages but are mainly focused on PHP.The first one could be entitled as "return as soon as possible"™. It may be summarized as changing:into:The benefit of writing code this way may not be obvious, but take a closer look at the next implementations of the setPassword() function of an imaginary User class:compared to:From this two implementations, we can see several benefits of the first one: