But they shouldn't have had to figure it out because there is no reason for the order of operations to exist. Mathematicians have an alternative to the mess above: parentheses. Placing the parentheses around the numbers makes the order in which they are to be performed clear. While the rules are likely as arbitrary as order of operations, they are at list simple and easy to remember. Everyone knows how to complete this problem:
((8-9)+34)/(67*(150,456,783-1)) = ?
Or this one:
(8-(9+(34/67))*150,456,783)-1 = ?
The parentheses provide an easy structure, a clear guide, for conducting mathematical solutions. No one needs to know the order of operations because there is a much superior means of expressing what you want to do.
Programming has a similar problem: order of precedence. I was reminded of this by an article about features of C# that one of the C# designers regretted. A specific order of precedence (essentially order of operations for operators in a given programming language) was among those items:
he && operator is also of lower precedence than equality, but that's a good thing. We want this:
if ( x != null && x.Y )
to be treated as this:
if ( (x != null) && x.Y )
and not this:
if ( x != (null && x.Y) )
That's great, but you already have a way of ensuring that already: the parentheses you used in the example you wrote. By enforcing order of precedence via parentheses, an entire class of bugs disappears. Now, unlike written mathematics, there may be a cost for enforcing order of precedence via parentheses, but if it exists (and I cannot seem to find much one way or the other) it is likely very small. Compared to the time spent finding weird bugs and figuring out what the code is actually doing, I would be the costs are insignificant.
Programming languages are, well, languages. They have grammar, and that grammar can either be clear or obscure. We should strive for clarity in our programming languages, just as we do in our written ones. You wouldn't leave out spaces between words or punctuation in any essay you wrote. When you rely on order of precedence, you are doing the equivalent. Don't. Make your programs as clear as you can.
Comments are closed on this story.