I'm going to pick on Chris Love
here because he disabled anonymous comments on his blog, and he only provides a partial RSS feed. It's a good thing I like his blog and am willing to click through on each post :)
Chris is an industry guru on ASP.NET in particular and certainly knows his away around a compiler. He recently posted about a clever VB "IF" statement to simplify some conditional logic in this post
. He's right on with the thought and this is completely valid, but its syntax is why I find VB confusing.
Some folks have questioned me as to why I find VB more confusing than C#, and this is a practical situation. So, in his post, the simplified code is:
MyFlag = (fields(5) = "Y")
...where MyFlag will now be true or false based on whether the flag is Y.
I've seen this a lot. And it's simplified, for sure. Applying Marcel's laws of code beauty
, it certainly is proportionate, and integrity-wise, it's fine too (arguably a little less). But clarity? It fails. This is because it's unclear as to whether we're looking for comparison or assignment. I could just as easily interpret this as field(5) is now equal to "Y" and MyFlag is now equal to "Y" via field(5), which is likely a type mismatch. The more verbose code of an if-else block is longer, of course, but more clear.
This assignment vs. comparison problem is a frequent coding mistake and why you see folks often code something like this:
if (null = myObject) ...
The comparison is still the same, but any assignment confusion would fail. As a side note, I don't like this syntax in C# as the compiler will catch these mistakes, and it leads to more confusion, such as:
if (5 >= myInt) ...
To me, this is just more confusing. In my brain, I have to stop and think, is myInt less than or equal to 5?
Add in an else block, and my brain starts thinking, wait ... if myInt is 6, where will I go? Oh to heck with it! Just rewrite the damn thing!
if (myInt <= 5) ...
Ah, there! That's better. So back to the original point, in C# (and other languages), assignment and comparison are different symbols. To accomplish this original example in C#, there are a number of approaches:
MyFlag = (fields(5) == "Y");
Certainly valid. A tad more verbose but more flexible where we might not want a simple true/false result:
MyFlag = (fields(5) == "Y") ? true : false;
I actually prefer the latter syntax, as it makes it clear we're after one of two values. And if anyone thinks this is purely academic ... I've seen a number of real world bugs due to this type of situation, unfortunately. (Not specifically what Chris posted, but more in general about confusion around assignment and comparison.)
OK, rant done. Thanks Chris for volunteering! :)