Main Content

Wimbledon Neck

Archive - Originally posted on "The Horse's Mouth" - 2005-06-20 08:58:36 - Graham Ellis

What use is the "+=" operator? Why did the language designers bother to provide it? Yet they did ...

In Perl and PHP

$number_on_bus = $number_on_bus + $goton_here;
becomes
$number_on_bus += $goton_here;

In Python

number_on_bus = number_on_bus + goton_here
becomes
number_on_bus += goton_here

In C and Java

number_on_bus = number_on_bus + goton_here;
becomes
number_on_bus += goton_here;

The += operator adds the result of evaluating the expression to the right into the variable named on the left.

The code is shorter, but there's more too it than that. It makes the code easier to maintain - it saves what we call "Wimbledon Neck" which is very appropriate for me to be writing about this week as the tennis championships are just about to start. If I write
$longvariablename = $longthingummyname + $some;
then anyone coming along to maintain the code has to take a careful look on both sides of the assignment to see whether or not the information is being saved in the same slot from which it was loaded or not; can you visualise the maintainer turning his neck to the left, to the right, to the left, to the right rather like watching a tennis volley from the side line? If the element being used is a member of an array (= list in Perl) or hash (= dictionary, = associative array) then that's all the more checking to do.

So - it may not come natural to you to code += (or -= *= /= etc) but please do so ... you're making life easier for those who follow behind!