By bloid
via jeremyjarrell.com
Published: Mar 19 2007 / 12:08
Did you know that & is not just for bitwise operations? You can actually use it in your standard conditionals, but there's a slight difference in how it behaves. This article will show you what that difference is.
Comments
daniel replied ago:
It's an important thing to know, even if it is somewhat common knowledge.
Lowell Heddings replied ago:
I figured this out years ago... through a typo.
senfo replied ago:
I love just about everything about C#, but this is one thing about the language that I really don't like because, having come from a hardware background, I still commonly use bitwise &, and it always catches me by surprise when a developer uses this operator to circumvent short circuit evaluation. Every single time I thought I had a use for it, I found a better solution that made my code a lot more clear. In other words, when I think the operator is useful, it's probably a very good sign that I need to rethink my logic. Obviously, I avoid using it for this purpose and have yet to find a *good* use for it. That's not to say that I might not eventually come across a place where it will be useful, however.
jtheory replied ago:
This is a feature copied exactly from earlier languages, including Java. I wish Java hadn't felt the need to include it in the first place.
It's one of those language features that may make you feel clever, but will have the guy maintaining your code in two years seriously wishing you had died in a horrible accident as a child. If your code is dependent on the side-effects from a boolean-returning method, you should fix your poor design, not use an obscure trick to get around the problem.
Nested ternary operators fall in the same category (supported in C++, Java, C#, etc.). Stuff like this is just cruel to your fellow programmers:
String value = "bar";
boolean wasWrong = true;
return "foo".equals(value) ? wasWrong ? "fooWrong" : "fooRight" : "bar".equals(value) ? "bar:"+wasWrong : "notFooOrBar";
-- but you still see it every once in a while. Because it saved a bunch of lines of code, right? As if these languages weren't compiled....
willcode4beer replied ago:
what would you propose as an alternative for bitwise operations?
Voters For This Link (6)
Voters Against This Link (1)