CELEBRATE EARTH WEEK
Save 70% on video training and simulators now through April 27*—use code EARTH. Shop now.
I've long been suspicious of code that depends on side effects, like depending on the order of expression evaluation. In the past, one had to worry about stuff like this because language standards often didn't specify expression evaluation order, which meant that code that worked when compiled with Microsoft C, for example, wouldn't work when compiled with Borland C (or vice-versa). I wrote some code like that today in C#, and wondered if it's considered bad practice.
The code in question looks up a value in a dictionary, and then tests a flag in the resulting record--all in a single conditional. The code looks something like this:
if (docIndex.TryGetValue(keyValue, out entry) && !entry.IsDeleted)
// do stuff
I know that the code would work as expected. That is, the call to
TryGetValue would be executed before checking the
IsDeleted property, and if the item was not found in the collection, the
IsDeleted check wouldn't be performed. By that measure, the code is definitely correct.
Now, whether it's clear is another question entirely. Certainly, it would be more clear to write:
bool bGotRec = docIndex.TryGetValue(keyValue, out entry);
if (bGotRec && !entry.IsDeleted)
// do stuff
Both do the same thing, and I'm not worried about efficiency, since any optimizing compiler would optimize away the Boolean temporary and end up generating the same code for both. But which is better? Does the addition of that Boolean make the code too verbose? Is the first example too terse?
What do you think?
Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.