- Feature Articles
- CodeSOD
- Error'd
- Forums
-
Other Articles
- Random Article
- Other Series
- Alex's Soapbox
- Announcements
- Best of…
- Best of Email
- Best of the Sidebar
- Bring Your Own Code
- Coded Smorgasbord
- Mandatory Fun Day
- Off Topic
- Representative Line
- News Roundup
- Editor's Soapbox
- Software on the Rocks
- Souvenir Potpourri
- Sponsor Post
- Tales from the Interview
- The Daily WTF: Live
- Virtudyne
Admin
Some people really, really like to kill the environment with their most inefficient way to implement the simplest algorithms. By this point I no longer think it's stupidity, it feels more like an intentional crime against humanity.
Admin
Boolean.Parse is over the top, but I prefer the simple if-then-else above it. Easy to read, easy to maintain, and the compiler can optimize as necessary.
Admin
In many places number of lines is still the main metric for coder productivity. Writing as obtuse and ineffective code as possible becomes the goal.
Admin
Boolean.parse("frist") is still one line. Perhaps this is a clever safeguard against #define true (random() < 0.999)!
Admin
C# doesn't have macros by design, so that's not an option. Plus you cannot overwrite keywords.
Admin
if ((someCondition || someOtherCondition) ? Boolean.Parse("true") : Boolean.Parse("false")) { return Boolean.Parse("true"); } else { return Boolean.Parse("false"); }
Admin
But such a #define is not possible in C#!
Admin
What The False?
Sometimes I wonder what truth can be returned by devs' minds.
Admin
Clearly,
true
andfalse
are magic constants and are to be avoided… e.g., by using clear name strings.Admin
I'm not willing to dig into the docs this morning, but I wonder how well
Boolean.Parse("true")
works when theCurrentCulture
is not one of the "en-whatever" variants. IOW in French, German, Russian, Arabic, etc.Admin
Any boolean comparison is unacceptable if it doesn't contain FileNotFound.
Admin
When I see stuff like this, I always wonder if it's generated code. I could imagine a code generator that produces something like "return {type}.Parse({value}). In fact, I was just looking at one yesterday. But if an actual, living person wrote this, I weep for my profession.
Admin
So, you got me curious about that- I hadn't even considered that behavior. But according to the docs,
Boolean.Parse
does a comparison against the propertyTrueString
andFalseString
, which are "True" and "False" respectively. Per the docs, only "True", "true", "False", "false" will successfully parse- which is interesting, because it implies that it's not a simple case insensitive comparison.Admin
Remember that strings are immutable in C# (.Net in general). And any strings that have the same value will share the same memory address.
This means that doing a simple compare vs "True" and "true" is just comparing against a couple of memory addresses and therefor very efficient.
Admin
Admin
No. Only interned strings share the same memory address:
https://sharplab.io/#v2:C4LgTgrgdgNAJiA1AHwAICYCMBYAUKgZgAIMTMB2PAbzyLpPXVvqvqObbtUwE4AKYJACmAOgAqAewDKggJZQA5nwCURALxqiAcSHAxwlcoDcHTt34AlIQDMhYIVADGQgKIBHCAEMANgGcBwuLScooqMNq6+hBChsambOZ8Vrb2Tq4ePv6C0UEyYPJKyuHcAAwiAJJQwHZQfDp6BspNcbhsAL6mpgAO+QBuntVkAGxkJREN0SrqAHzx9ABE2ULzQQCqXV12KgDaJQC6RIhE88LzJrhtQA
Using string.Intern on a string will search the intern pool to find the "True" used by System.Boolean, which then has the same address
Addendum 2024-09-26 09:46: String comparison does check memory addresses first, but if they aren't it does a char-by-char comparison (possibly vectorized).
Admin
Pretty sure compilers are just as good as optimising the "return a ? b : c" version as the "if (a) then { return b; } else { return c; }" version. Possibly even better in some cases (it'll be fairly clear to the compiler (as well as to the reader!) that there's only one return path, for instance).
Admin
During development, the verbose option of:
can be handy for setting a breakpoint on (only) one of the branches when debugging.
Admin
It's a bit more complicated like that. For starters all literal and const strings are guaranteed interned (which applies to those boolean constants - actually, they are readonly references to literals for performance reasons, but that's another sack of beans).
Now during the old .net framework 1.x days the compiler interned strings very fast, usually at least before a string equality check happened. That's the reason why switch statements worked in C# while it was not possible in Java. Now with 2.0 they changed the string handling; turns out a lot people don't read the manual and did insane stuff like building stuff in an iteration using operators instead of StringBuilder. So from that moment on strings were actually rarely interned automatically and they put a lot effort into keeping features like the switch statement around without loosing to much of the previous performance.
Now one very important thing about string is that most of it is actually implemented directly by the compiler for releases, this is especially true for equality checks and how and when basic methods and operators apply. Things actually got a lot more complicated recently due to how interpolation is actually handled by the compiler. So just looking at the source code will not help you out there because it rarely applies and there is a ton of direct implementations done by the compiler circumventing using string.operator== or string.Equals ;-)
Admin
I am of the same opinion, but I'm wondering whether I may be wrong. I favoured the clarity over brevity. However, I can see why the one line variation might be the clearer option.
Consider the case, where a boolean variable is being set, rather than it being a return statement. I find that I might be searching for when that boolean variable is referenced. I would note that the one line variation has the benefit of being clearer when included in the results of such a search. Being on a single line avoids the need for the context. In addition, with the multi-line version, there'd be two search matches and a need to realise that they're closely related, requiring context, again.
Admin
Feel free to weep. I taught programming for decades mostly for evening classes. This generally meant I got people with day jobs as programmers trying to pick up something new. Naturally, this is a good thing. But at the same time I got to find out just how little so many programmers knew. It was very common for programmers to not grok boolean values. "If ( boolValue == true )" was, unfortunately, a very common construct. The mentioned ternary resulting in true/false turns up more often that you might believe. I've found that even veteran programmers can't adequately tell me a professional definition of a byte. ("Um.. it's like... a character?") For progammers in the C language style category, many don't really understand bracing rules. As I write this, I have some 26 year old C++ on my screen littered with things like "if (keys_found == 4) { break; }". I literaly copied and pasted that into this response. No line break and unnecessary braces. Considering the age of the and that about 30 years ago I taught for a semester on site at the company I'm presently working at, this might have been written by one of my students. I certainly hope not.
And I hope I don't sound like I'm railing on programmers for ignorance. There's so much to this business that best minds can't know 1/10 of a percent of what there is to know. What I object to is the lack of awareness. Has this progammer from today's story never looked at anoyone's code other than his own? Did the programmer from the clip I put above never notice that other programmers have dispensed with the curly brace and then wonder about his own usage? Couldn't the manager I once worked for take a few minutes to understand the ternary operator instead of trying to ban its use in our department?
Admin
re:
"turns out a lot people don't read the manual and did insane stuff like building stuff in an iteration using operators instead of StringBuilder"
One thing compiler writers and language committees need to learn is that NOBODY reads the manual. a = b + c is how people have been taught to add things together and joining strings is like adding them (in people's minds anyway). Telling them to use StringBuilder is not going to cut it. It's not nearly as intuitive as using +.
Admin
If you need all that for ease of reading and maintenance, it indicates that you need to get better at both.
Admin
Well, most languages are sane enough to overload
+
for string concatenation (and then some are insane with type promotion). I shudder to go back to 80s makeshift languages and boggle whether it's juxtaposition or dot for concatenation. At least they predate Unicode or they'd use ZERO-WIDTH JOINER as the concatenation operator.So at that point, it's not really the user's fault anywhere at all that the implementation is so wildly inconsistent. (Also see: bitshift operator << on streams.)
Admin
Oh no, you forgot the obligatory aspect for "File Not Found"!
Admin
'There are many variations on it, all of which highlight someone's misunderstanding of boolean expressions. '
I just got into programming and until now thought this is a good way to check for conditions, what's the correct way?
Admin
I know I'm a bit late, and I know it's unusual to answer serious questions seriously here, but anyway: The point (which the article and most comments implicitly refer to) is that in most programming languages, Boolean expressions are first-class values just like integers, and can be used as such. So, assuming(*) that "someCondition" is in fact a Boolean value, it can have only two possible values, true and false, and there's no need to convert it to these same values. So you can just do
Another misconception that e.g. Argle's comment alludes to is that conditions (e.g. in if-statements or while-loops) always need a comparison operator like "If ( boolValue == true )". Again, that's unnecessary. If "boolValue" is in fact a Boolean value, "if (boolValue)" will do just fine.
(*) Strictly speaking, the article never mentions whether "someCondition" is actually a Boolean value. Some languages (let me take C++ for the following examples) can convert some other types such as integers to Booleans automatically. So this will still work:
However, combined with automatic type-deduction, an explicit conversion may be necessary:
This would return a as-is and deduct the return-type as "int". If you want it deducted as bool, you need an explicit conversion. "return a ? true : false;" would work, though a normal type-conversion is usually preferable (and works for any type where conversion is possible, not just for the special case of bool), i.e. "return bool (a);".
So again, the two forms presented in the article are basically never preferable. (Unless, as some comments always seem to mention when this topic comes up, if you need to set a break-point and use a debugger that doesn't support conditional break-points apparently.)
Admin
Perhaps the IDE said that
return x ? true : false
is bad, and the developer used Boolean.Parse to outsmart the IDE?Admin
Some style guides require braces every time as a way to reduce the rate of blunders. It's not something worth complaining about.