Posted by Peter Fox on 03/21/06 11:22
Following on from Jim Michaels's message. . .
>This is a simple coding tip I learned to prevent comparisons from becoming
>assignments (and this becoming a hair-pulling session during debugging):
>
>in comparisons, try to put your constants on the left hand side of the
>operator and variables on the right hand side.
>example
>if (3==$x) {
> //do something
Here is a precis of my standard lecture (shortly to be a book) on
equals.
The use of = and == is *full* of traps
$totalCake = 100;
$slices = 7;
$slice = $totalCake / $slices;
$cakeLeft = $totalCake;
while ($cakeLeft != 0){ // will this loop terminate? Always?
$cakeLeft = $cakeLeft - $slice;
}
// Crumbs!!
A way to 'burn-in' mental processes in order to distinguish = and == is
to 'say' "=" as one word and "==" as two. For example "equals" and "is
equal" (or "equals" and "equal to") and to get into the habit of
'saying' conditional statements using the two word form.
$a =[equals] $b;
if($a =[equal]=[to] $b){ ...
Are we asking if $foo and $bar are the same object or do all the
properties of $foo match those of $bar? Do you have the same car as me?
Does this mean "Do we own the same bit of metal?" I have a document
which I photocopy and give the copy to you. Do we have the same
document? Yes and No. Yes : Same words. No : Different bit of paper.
--
PETER FOX Not the same since the deckchair business folded
peterfox@eminent.demon.co.uk.not.this.bit.no.html
2 Tees Close, Witham, Essex.
Gravity beer in Essex <http://www.eminent.demon.co.uk>
Navigation:
[Reply to this message]
|