Re: Which is better coding style...

From: Date: Fri, 20 Apr 2001 11:22:32 +0000
Subject: Re: Which is better coding style...
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-49540@lists.php.net to get a copy of this message
On Thursday 19 April 2001 22:31, you wrote: > Definitely the second style :) > > (If we were talking about C(++) then the first would have even been > forbidden by my companies coding standard as well as several coding > standards of other companies I worked for.) <put_on item='asbestos battle armor'> Urgh That's a rule back from ye olde COBOL days ------------------ function blah() { switch( $bob ) { case 1: return "this"; ------------------ This clearly says: "If $bob == 1, we return "this" (no further processing needed)" Your preferred style: ------------------ function blah() { $retval = ""; switch( $bob ) { case 1: $retval = "this"; break; ------------------- .. says "If $bob = 1 set $retval to "this" and continue processing" That's misleading. And harder to understand, because it requires that you read through the *entire* function up to the "return" at the end, keeping track of which parts were processed in your case etc. Taking this to a more complex example, what is more readable? ----- Ex 1 --------- function WriteIt ($Basename, $Data) { $retval = true; $FP = fopen ("$Basename", "w"); if ($FP) { if (fwrite ($FP, $Data) == strlen ($Data)) { fclose ($FP); $FP2 = fopen ("$Basename.copy", "w"); if ($FP2) { if (!(fwrite ($FP2, $Data) == strlen ($Data))) { $retval = false; } fclose ($FP2); } else { fclose ($FP); $retval = false; } } else { $retval = false; } } else { $retval = false; } return $retval; } ------------------- or this: ------- Ex 2 -------- function WriteIt ($Basename, $Data) { $FP = fopen ("$Basename", "w"); if (!$FP) return false; $Ret = fwrite ($FP, $Data); fclose ($FP); if ($Ret != strlen ($Data) { return false; } $FP2 = fopen ("$Basename", "w"); if (!$FP2) return false; $Ret = fwrite ($FP2, $Data); fclose ($FP2); if ($Ret != strlen ($Data) { return false; } return true; } --------------------- </put_on> > The reason is this - a function has one entrypoint (duh) True (duh) > and one exitpoint. False. > Jumping out of a function somewhere in the middle leads to > unmaintainable code See example above. > But, as with the indenting and bracket placing, > it is a matter of religion. Now that's something we agree on :) -- Christian Reiniger LGDC Webmaster (http://sunsite.dk/lgdc/) Google results 1-10 of about 142,000,000 for e. Search took 0.18 seconds. - http://www.google.com/search?q=e

« previous php.general (#49540) next »