Zero the value is not

One of my pet-peeves is code written like this,

if (0 != value) { ... }

This reads backwards to me. I hear echoes of Frank Oz in my head, "if zero the value is not". As cute as this dialect is coming from a pointy-eared muppet, it still takes a bit to translate back into the more common English phrasing, "if the value is not zero". It seems programmers who insist on writing in this style have forgotten that their source should be readable as well as executable. Don't force your readers to have to do grammar gymnastics as well as having to decipher your algorithmic gynmastics.

Once upon a time, this was considered good style in order to avoid accidentally writing something like,

if (value = 0) { ... }

In C#, this is illegal. In most (all?) modern C and C++ compilers, this will generate a warning. (You do compile with warnings reported as errors right?) There ceases to be a good reason to write test expressions backwards. Let's let this style rest in peace.

Even if you think the above form has some redeeming value, let's all agree that any programmer that voluntarily writes something like,

if (false == value) { ... }

should have an electric shock sent directly through their keyboard.

08/31/2008 7:55 PM

The out of the box settings in VS2008 for C++ do not generate an warning or error for a conditional coded like: if (value = 0) { ... }

Thankfully C# doesn't allow some of the crazy syntax that C/C++ does.

Aaron | www.wiredprairie.us/blog | coderAT NOSPAMwiredprairie dot us

09/01/2008 4:54 AM

A useful construction I use often, which goes against the backwards syntax you dislike (actually I dislike it in an if statement) is (VB6/VBA):

Select Case 0
...

or

Select Case True
...

Jon Peltier | http://PeltierTech.com/WordPress/ | jonpeltierAT NOSPAMgmail dot com

09/01/2008 8:48 AM

I think you'll die when you see this code.

if( success1 && success2 && success3 )
return true;
else
return false;

09/01/2008 11:02 AM

This is not as bad had it been written,

if (success1 && success2 && success3)
return false;
else
return true;

I dislike this style as well because it requires so careful reading.

Chuck.

Chuck Jazdzewski | www.removingalldoubt.com | chuckjAT NOSPAMmicrosoft dot com

09/01/2008 6:48 PM

Both

if (false == value)
...

and

if (value == false)
...

are non-optimal. Both should be replaced with

if (!value)
...


David Ching | http://dcsoft.com | dcAT NOSPAMdcsoft dot com

09/02/2008 12:29 AM

If you only ever write code in C# or Visual Basic, you might have a point.

But the world is not a disc, and some need or want to switch between C#, C++/CLI, Managed C++, and C ever so often.
Your rant is just about a single piece of a defensive coding strategy, taken out of context, and which in itself is neither a hassle for a programmer, nor a major stopping point to any experienced code reviewer.
In fact, it either shows somebody cares about const and other traits of operands, is just blindly following some ancient coding guidelines, or has simply copied the code from a book or blog.
All of which are quite telling and transfer more information than your "natural" style.

Your argument probably also extends to "m_" or "s_" prefixes for instance or static member variables, and Hungarian notation in C++. These are all devices to keep programmers thinking about their code and recognizing wrong patterns early.

As far as electric shocks go, they should hit the ones having "if" and the depending statements in the same line.

Henry Boehlert

09/02/2008 12:48 AM

BTW, I was just wondering:

const.Equals(variable)

-or-

variable.Equals(const)

Any preferences?

Henry Boehlert

09/02/2008 11:00 AM

> Any preferences?

This gets more into practics than style. All things being equal you should favor "variable.Equals(const)" but, sometimes, if the variable might be null, you might want the other form but I really perfer using object.Equals(variable, const) in those situations.

Chuck.

Chuck Jazdzewski | www.removingalldoubt.com | chuckjAT NOSPAMmicrosoft dot com

09/02/2008 11:47 PM

how about declaring variable that expresses the intent

bool valueIsNonZero = (value != 0)
if (valueIsNonZero)
....
else
....

Kalpesh | mailto:shahkalpeshAT NOSPAMgmail dot com | shahkalpeshAT NOSPAMgmail dot com

09/04/2008 6:02 AM

This is one of my peeves as well. And while yes, many people write in different languages, they should change idiom when they change language too. Otherwise you get "C# with a Java accent" and the like.

Jon Skeet | http://msmvps.com/jon.skeet | skeetAT NOSPAMpobox dot com

09/04/2008 9:30 AM

Yes, this is definately a cargo cult in C# from C++ and should be avoided.

Peter Ritchie | http://www.peterritchie.com/blog | removingAllDoubt dot comAT NOSPAMpeterritchie dot com

09/04/2008 4:04 PM

Actually, it's not quite safe in C#. Try running this.

class X { static void Main() {

bool a=false;
bool b=true;
if (a = b )
System.Console.WriteLine("should not write this");
}
}

It's safe when they're not both bools, though. This was a conscious limitation, because expressions are necessary inside if-tests, even if silent-casts-to-bool can be eliminated.
Dan

dan | mailto:fooAT NOSPAMbar dot com | fooAT NOSPAMbar dot com

09/04/2008 8:13 PM

if(value == false) is a broken window.

futureturnip | jeffkwak.com | jeff dot kwakAT NOSPAMgmail dot com

09/06/2008 3:34 PM

Yes I'm an old x C++ junkie ... and while I've manged to shed my m_'s and hugarian notation, I still to this day keep using

if (false != value) and if (0 != value)

Even if the logic is "backwards" as you claim, it has one advantage. 0 and false are nice and short and helps keep the operator snuggled up nice and close to the keyword. Instead of

if (GoGetTheValueToBeTestedByDoingThingsWithTheseFiveParameters(parameter1,
parameter2,
parameter3,
parameter4,
parameter5) != false)


And while it may require a tiny amount of additional thought, you don't need to change the batteries in your mouse and scroll out to column 1812 just to see what you're comparing against.

Nick | mailto:nfiorelloAT NOSPAMcfl dot rr dot com | nfiorelloAT NOSPAMcfl dot rr dot com

09/06/2008 3:38 PM

Oh, and for the record *I* still try to live in 80 columns, however the code I've inherited was not so lucky. :-)

Nick | mailto:nfiorelloAT NOSPAMcfl dot rr dot com | nfiorelloAT NOSPAMcfl dot rr dot com

09/07/2008 4:56 AM

Uh... I remember some nasty property in a good old Delphi's DB Express class who read like IsNotDontRememberWhat, and the funny things that happened when you had to negate its value...

Ian Marteens | freyalang.blogspot.com | ianAT NOSPAMmarteens dot com

09/08/2008 7:12 AM

I've seen this a few places and wondered if it was just me. Another related practice I find helpful is to "think positive", and whenever possible, favor the 'true' condition ie:

if (shouldDoSomething)
{ doSomething(); }
else
{ dontDoSomething(); }

Takes fewer brain cells than:
if (!shouldDoSomething)
{dontDoSomething();}
else
{doSomething();}

This extends to other areas as well. ie:
this.IsValid
this.IsActive

are (IMO) usually more easily comprehended than:

this.IsInvalid
this.IsInactive

Obviously some places this doesn't make sense, but where it does I find "think positive" helps keep things more readable for us boolean-challenged :)


Daniel | mailto:drootAT NOSPAMlifecycle-solutions dot com | drootAT NOSPAMlifecycle-solutions dot com

09/08/2008 9:15 AM

I would have to agree with Nick. I too am an ex-C++ programmer. I used to hate the 'if (false == foo)' syntax when I was a junior programmer. Even after a gifted senior programmer explained why it was a good thing (thanks, Stu!), I still didn't like it and I didn't use it for a long time. The reason I switched was because I had a killer bug that took me days to find. My bug produced a random GPF every now and then, and was caused by a missing equals character in an if statement. After learning that lesson, I started switching my comparisons around and I keep them like that to this day.

Damian Powell

09/08/2008 10:12 AM

Damian,

> ... and was caused by a missing equals character in an if statement

This is certainly the error this style was intended to prevent but, in most cases, this is illegal in C# (except in the bizaar case of assigning booleans noted above by dan) because of C#'s more strict typing. This style has no value in C#.

I am far from a C++ expert and if this is considered good style in your shop then you should use it. If it were my shop, however, I would insist that the C++ warning for this be enabled (actually, I would insist all warning be enabled) and insist that all code compile clean, without warnings.

Chuck.

Chuck Jazdzewski | www.removingalldoubt.com | chuckjAT NOSPAMmicrosoft dot com

09/08/2008 10:30 AM

Nick,

>if (GoGetTheValueToBeTestedByDoingThingsWithTheseFiveParameters(parameter1,
parameter2,
parameter3,
parameter4,
parameter5) != false)

This code is too far gone for a simple inversion of the test to fix. The long method name with multiple parameters on a single line is symptomatic of much deeper problems in the code. I would be very suspect of such code if I were reviewing it. The only thing I would consider worse is if you through in some var and/or out parameters.

At the very least this code should be broken up into multiple statements such as,

var importantResult = GoGetTheValueToBeTestedByDoingThingsWithTheseFiveParameters(parameter1,
parameter2,
parameter3,
parameter4,
parameter5);
if (importantResult) { ... }

Simply inverting the test does nothing for the readability. Refactoring the code would do much more.

Chuck.

Chuck Jazdzewski | www.removingalldoubt.com | chuckjAT NOSPAMmicrosoft dot com

09/08/2008 10:31 AM

Amen, brother! These inverse statements are unnecessary and confusing to read.

09/08/2008 4:37 PM

I have to totally disagree, when you come to 'scan' some code written a while back or by somebody else it is a lot easier if the statement is inverted.

if (false == ResultOfSomeCall())
{
...
}

Will be syntax highlighted, the if and false show up clearly next to each other in different colours so you know without reading the line that the statement block will be executed when something is NOT true.

With this:

if (! ResultOfSomeCall())
{
...
}

It's very easy to miss that single character when you're just scanning through a method to get the idea of what it's doing. Oh and to the poster who suggested it, this will not be any more efficient, in fact logically if unoptimized would result in one operation to invert the boolean (the '!') and then a second to check if it was true (the 'if') so should be _less_ optimal. But of course the JIT will not actually do that.

if (ResultOfSomeCall() == false)
{
...
}

pushes the comparison and constant too far from the 'if' so you have to scan and read more. The more you have to carefully read, being human, the more you will miss, leading to less reliable code, especially if the bug is in some rarely used code path and doesn't show up until it's been deployed for months.

Of course, coding style is part religion, so each to their own!

David | mailto:davidnAT NOSPAMsytelco dot com | davidnAT NOSPAMsytelco dot com

09/08/2008 5:44 PM

Wow. This article was listed in my VS Start Page as extolling the virtues of readable code. Instead, it's a rant about one of the more controversial stylistic decisions that is, like most stylistic decisions, idiosyncratic.

I like the constant-first comparisons. I always have. It reads backwards to you; fine. It isn't any more or less sensible than any of the other code conventions we use daily.

In some languages, it protects against an easy error. That the language is to blame is moot: I work in the real world and I work on teams. I want junior programmers to use techniques that protect my project, I don't trust that every developer has warnings as errors (especially in with recent libraries generating errors when used with shipping code that we won't take the risk to change), and I like to see the test condition first.

Style is style. When I think about improving code readability, I'm far more interested in naming, operator choice, overloads, side effects, common closure of interfaces, accurate comments, factored functionality, data abstraction, careful distinctions between tight and loose coupling, and a host of things that come before infix operator order.

Id it's a pet peeve of yours, great. I have my peeves (unbalance curly braces, using "this->" in C++, any use of ->* or ->., etc.) and I'll use rvalue-on-the-right when I'm working with your team. Happy to.

And if protecting my project and my client, preferring a style that isn't yours, and knowing the difference between an lvalue and an rvalue make you determined to shock me, at least let ground first :-)

Seth Morris | mailto:sethAT NOSPAMpobox dot com | sethAT NOSPAMpobox dot com

09/08/2008 10:48 PM

Seth,

I was also surprised, first that one of my posts as featured on VS start page, and second, by the slug they used to characterize it. I have no control over that. I appologize for the false advertisement.

I regret even mentioning C++. As stated above, I am far from an expert in C++. My post was really directed at C# programmers using this style, which is not clear from the text of the post at all.

Chuck.

Chuck Jazdzewski | www.removingalldoubt.com | chuckjAT NOSPAMmicrosoft dot com

09/09/2008 12:38 AM

Maybe it makes sense for Arabic C# programmers (right-to-left languages). ;-)

:-)

Jacques | http://openlandscape.wordpress.com | jacquesduAT NOSPAMnedbank dot com

09/09/2008 1:46 PM

As mentioned by Henry earlier this was a defensive mechanism in C++. The main point was that C++ would allow a statement like:
int value;

if ( value = 0 ) ...

As this assigned 0 to 'value'. But to avoid the snafu, one was told to compare constants left-to-right, by writing it as :

if ( 0 = value ) ...

this way the C++ compiler would flag it as an error (bec/ you cannot assign a value to a constant/literal). Fortan, I believe, had the same issue. I think this was also the cause of one of the Hubble problems ....

There are many leftovers from previous languages, ie., Hungarian/Pascal casing for naming, where you place the brackets, etc. .... All religious issues in coding ... and beauty is in the eye of the beholder....

I would be more concern with code that was not solid or with no supporting test-cases than the issue brought up here ... it is noise.

In fact, I would suggest that one write a FXCop snippet to check for these subtities before you check in the code and you won't have to look at it . :-)



bill | mailto:bjanderson70AT NOSPAMhotmail dot com | bjanderson70AT NOSPAMhotmail dot com

09/09/2008 5:25 PM

bill,

> In fact, I would suggest that one write a FXCop snippet to check for these subtities before you check in the code and you won't have to look at it . :-)

This would have to be StyleCop but yes. For my team it is already the case. The problem is I review code for other teams as well for which I don't exert as much (any?) control.

Like my post says, it is a pet-peeve of mine. I find it jolting to read, like nails on chalk-board. I believe it has no useful purpose in C# code. It very well might have use in other languages but it brings no value to C# because the error it was trying to prevent is caught by the compiler.

Chuck.

Chuck Jazdzewski | www.removingalldoubt.com | chuckjAT NOSPAMmicrosoft dot com

09/10/2008 6:25 AM

I expected an article on code readability. Instead, I read an article on a pet peave.

Good journalism?

Any programmer worth his salt should be able to read:

if(null != myObject)
{
Do Something
}

Mike Q | mailto:michael_quickentonAT NOSPAMfarmfamily dot com | michael_quickentonAT NOSPAMfarmfamily dot com

09/10/2008 5:06 PM

Mike,

> I expected an article on code readability. Instead, I read an article on a pet peave.

As noted above, I have no control over how others (including those employed by the same company) choose to characterize my posts. If you read the post carefully you see I never intended this to be anything other than a vent about one of my a pet-peeves.

Chuck.

Chuck Jazdzewski | www.removingalldoubt.com | chuckjAT NOSPAMmicrosoft dot com

09/11/2008 7:34 AM

Chris,

I agree completely about refactoring. As I mentioned in my followup, I strive to constrain myself to 80 columns. But I've shuddered over lines of code that were 2000+ characters long.


Nick | mailto:nfiorelloAT NOSPAMcfl dot rr dot com | nfiorelloAT NOSPAMcfl dot rr dot com

09/11/2008 12:55 PM

I started writing constant-first as a defensive mechanism in C++, but I have found that I actually prefer it, even after moving to C# where it is not "necessary" for defensive purposes. There is nothing "backwards" about it; it is simply one of a number of ways of expressing a comparison. If you don't prefer it, that's fine. But there is no reason to insult those of us who do by accusing us of ignoring readability. Readability is in the eye of the beholder.

As far as "if (false == value) { ... }" deserving an electric shock, that again is a matter of opinion. The "!" operator can be very difficult to see when skimming code; "false == value" much more clearly expresses the programmer's intent.

Try to remember that not everyone thinks the way you do, and your pet peeve is someone else's best practice.

David Nelson | www.commongenius.com | davidAT NOSPAMcommongenius dot com

09/11/2008 1:32 PM

I do use this style. When I am scanning code quickly, it helps when the constant is on the left. A constant on the right is tiresome when dealing with thousands of lines of code to figure things out.

James | http://www.jamespaulp.us | jamespaulpAT NOSPAMgmail dot com

09/11/2008 4:46 PM

I really like using the '!' instead of '== false' because it reads so well. You see the '!' and you mentally verbalize 'not'. The fact that it is the most concise and terse in number of characters is what I meant when I said it was 'optimal'. I was not referring to the object code that it was compiled down to.

For all those who think the '!' is too easy to miss: adjust your font/colors for punctuation and you will have no problem.

For C/C++ programmers programming Win9x, both these are considered illegal:


BOOL b;
if (TRUE == b)
...

if (b == TRUE)
...

This is because BOOL is an int, and TRUE is a #define and is defined differently and does not always equal 1.

The only correct way to express this is

if (b)
...


So getting rid of the '==' is a habit many Windows programmers have gotten used to, when comparing BOOL's.

David Ching | http://dcsoft.com | dcAT NOSPAMdcsoft dot com

09/11/2008 6:28 PM

David,

> "false == value" much more clearly expresses the programmer's intent.

I totally disagree. This is a clear indication that the programmer is not thinking in Boolean logic. There is no place for the equals operator in a Boolean expression. It is totally foreign. The only time it makes sense is when you are treating the bool as a value and not a logical result. For example,

bool SomeProperty { get {...} }
set {
if (this.someProperty != value) {...}
}
}

This makes perfect sense. The following,

if (value == otherValue) { ... } else { ... }

also make perfect sense assuming otherValue is some cache version of value (though the != is much more common than ==).

But the "false == value" is using value as Boolean result, not a value; it no longer maps to Boolean algebra. Comparing to "true" or "false" mixes the metaphors. It treates value as a "value" not a Boolean expression, but the programmer meant it to be a Boolean expression. This only "better expresses the programmers intent" if the programmer was treating this bool as a value not as a Boolean expression, which is quite rare and I have never seen it when one of the sides of the expression is a constant.

What expresses the programmer's intent best using Boolean algebra when you mean a Boolean expression. This means using the "not" operator "!". This expresses clearly that you want to do something when the value is not true.

if (!value) { ... }

Additionally this is terrible style in C and C++ as pointed out David above.

if (FALSE == value) { ... }

is valid but the programmer that writes,

if (TRUE == value) { ... }

is in for a big surprise. This of course is no reason to to avoid it in C# but there isn't even an historical argument for using this particual style in C#.

> "!" operator can be very difficult to see when skimming code

That is true and it was a bad choice for operators made a long time ago but is no justification for using an obtuse replacement. Especially since you need to read so carefully to distinquish between,

if (false != value) { ... }
if (true == value) { ... }
if (false == value) { ... }
if (true != value) { ... }

These just make my head hurt. If you stick to only using if (false == value) { ... } you might have a point. It is easier to see than (!value) but it would be difficult to preventing the other three if you allow one of them.

Also, I found that skimming code is a bad idea when reviewing it. All kinds of things will skip past you to bite you later on, so a convention that helps me skim code is of little value. I prefer a style that helps me read the code without having to perform mental gymnastics.

Chuck.

Chuck Jazdzewski | www.removingalldoubt.com | chuckjAT NOSPAMmicrosoft dot com

09/11/2008 11:24 PM

Chuck,
First of all, I recommend you find out who you must have wronged on the VS Start Page links committee to deserve such a vindictive act of cruelty... :)

That aside, I use:

if (false == boolValOrExpr)

for the express purpose of readability as opposed to:

if (!boolValOrExpr)

as I have often overlooked the tiny ! operator in code reviews.

However, in my opinion that is the _only_ time a boolean constant (true, false) should ever be used in a boolean comparison expression _on either side_ of the comparison operator. The remaining examples you gave above also make my head hurt.

This following doesn't hurt my head so much as it hurts my pride in being a member of the programmer community:

if (true == value)

ARE YOU KIDDING?! You might as well do something like:

if ((intValue == 4) && (intValue == (2+2))) uhhhh, okay...

And the others:

if (false != value)
if (true != value)

Well... why not just make it even harder to read while you are at it like:

if (!true != value) & (!false != !value))

(note the bitwise & thrown in for kicks ..hehe)

Well, now I got to rant too. Thank you for the opportunity. I can rest well tonight.

- Ranty.

Ranty | mailto:RantyAT NOSPAMRant dot net | RantyAT NOSPAMRant dot net

09/12/2008 11:37 AM

Ranty,

I must admit I am not as opposed to (false == value) as I was when I wrote the post. Maybe I can be persuaded to reduce the voltage a bit...

Although I would still not use it and still find it jarring, I can see some value in it. If "false =" was consistently used as an idiomatic replacement for "!value" I could probably get used to it. I will probably never get used to "0 != value" or the especially jarring "0 < value".

The reason I find these jarring is because they are backwards. I realize people above have stated that "...[t]here is nothing 'backwards' about it..." but, for good or bad, I speak English. English is an order dependant language were the subject is to the left of the verb, the object is to the right. In the comparison "0 != value" the subject is "value" and the object is "0". Writing it "0 != value" is writing "if 0 is not the value" which is nonsensical. This implies that 0 might sometime change to be the value when the thing that might change is value. If your comments are in English, the code should use English conventions.

The only time I use constants on the left of the comparison is something like,

if (1 <= i && i <= 100) { ... }

which translates to "if i is in the range of 1..100" which scans a bit better than,

if (i >= 1 && i <= 100) { ... }

which laboriously says the same thing. I like the fact that in some langauges, like Fortress, this can be written something like,

if (1 <= i <= 100) { ... }

Pascal has an even better way to write this,

if I in [1..100] then ...

which translates very nicely. Unfortunately this is not reliably translated very efficiently by the compiler so should only be used if you know your compiler translates this well.

Chuck.

Chuck Jazdzewski | www.removingalldoubt.com | chuckjAT NOSPAMmicrosoft dot com

09/13/2008 12:23 AM

public static bool operator !=(Chucky operandLeft, Chucky operandRight)
{
return ( operandLeft == operandRight) == false;
}

/*
Can I run the above fragment by you? (Beware the trap.)
*/

Lauren

09/14/2008 4:36 PM

> You do compile with warnings reported as errors right?)

Wrong. Occasionally on complex code compilers produce bogus warnings that are impossible to get rid of or even disable. In this cases having "warnings as errors" leads to a wild goose chase of compiler ideosyncrasies (sp?). Letting these warnings slide is the least of two evils.

Ivan

09/14/2008 5:05 PM

Ivan,

I thinkyou are making a bad trade-off here. In my experience, the warnings that you describe are few and far between; where as warning that point out real problems occur regularly.

There must be a way to flag new warnings immediately. One way to do that is having warning as errors, don't let the programmer continue until they deal with it. Another is to post process the compiler result comparing the warnings to the last result. If they are the same (modulo line number movement) then continue. If they change, require the programmer fix the new warning or update the approved list.

Warning often point out real problems. I believe you let them slide at your own peril.

I have not encountered a warning in C# I could not disable either by adjusting the code or using a pragma. This is why we use warnings as errors in my group.

If this doesn't work in the compiler of your choice, I highly recommend post-processing the warnings as described above.

Chuck.

Chuck Jazdzewski | www.removingalldoubt.com | chuckjAT NOSPAMmicrosoft dot com

09/15/2008 7:58 AM

Coming from a C/C++ background, then changing companies that writes primarily in VB (boo), I've seen code as follows:

If Not IsNothing(Not Object.Parse("|")) Then ...

In English, double negaitves are grammatically incorrect, so what makes it acceptable in coding?

As far as the post, I agree that it is a pet peeve using bangs in statements. I also prefer basing everything from true statements, even if I am not doing anything from a true statement.

bool b = something();
if(b) {
} else {
b = false;
}

My reason is that when I've had to train new programmers, they seem to get confused and have to break the statements apart when using nots.

People just have too much of a tendency to overuse the ability to put multiple tests on a single line.

Jarrod | mailto:Jarrod_RamseyAT NOSPAMyahoo dot com | Jarrod_RamseyAT NOSPAMyahoo dot com

09/15/2008 8:54 AM

"...but, for good or bad, I speak English. English is an order dependant language were the subject is to the left of the verb, the object is to the right."

This is absolutely true. I also speak English. But I don't program in English; I program in a number of languages, including C++, C#, and VB.NET, among others. Each of these languages has its own idioms and conventions, which are appropriate to the individual language. There is no reason to expect those programming idioms to be the same as a natural language to which those programming languages are only tangentially related.

David Nelson | www.commongenius.com | davidAT NOSPAMcommongenius dot com

09/15/2008 9:14 AM

Jarrod,

> if (b) { } else { ... }

I certainly would prefer this to using (false == value). It is much more verbose but still treats "b" as a Boolean.

My group doesn't seem to have difficulty seeing the "!" but if that becomes a problem I will keep your convention in mind.

Chuck.

Chuck Jazdzewski | www.removingalldoubt.com | chuckjAT NOSPAMmicrosoft dot com

09/15/2008 9:26 AM

David,

> There is no reason to expect those programming idioms to be the same as a natural language [...]

I agree but, given the choice between using one that does and one that doesn't, I prefer one that does.

As noted above, I find using an idiom that goes against natural langauge conventions distracting to read. When reading code, unnecessary distractions bother me.

I believe that when writing code you need to be aware that, not only does the machine need to execute your intent correctly, your intent must be clearly communicated to the reader. Following Enlish convention, when possible, makes code easier to read (assuming the comments are also in English).

Chuck.

Chuck Jazdzewski | www.removingalldoubt.com | chuckjAT NOSPAMmicrosoft dot com

09/15/2008 11:13 AM

To all those who prefer (false == value) over (!false) because it's more readable-- why don't you give COBOL a try? Talk about reabability! (at least in English) :-)

Richard E. | mailto:richard dot ernstAT NOSPAMharlandfs dot com | richard dot ernstAT NOSPAMharlandfs dot com

09/16/2008 10:03 AM

Personally I think we are reading a computer code and not any chapter book. As far as we remember this fact then we don’t have to send an electrical shock to the coder who has trained themselves for safe coding.

Sunil Vishwas | mailto:SunilVishwasAT NOSPAMHotMail dot Com | SunilVishwasAT NOSPAMHotMail dot Com

09/16/2008 11:05 AM

Oops, as an English speaking person from an obscure part of Britain (Burtonwood) your posts struck a chord. 'Wooders routinely speak in double negatives or more - as in "Old Albert ain't not been around here no more."

I was surprised to discover that my heritage had expressly prepared me for the ravages of Boolean code writing. I could never understand why others had need of the defensive programming styles you describe.

And, yes, I must admit to being guilty of things like :-

while ((a=getData(out x))||(b=getOtherData(out y)) ... ad infinitum)
{
if (a){ .. use x }
if (b){.. use y }
}
.. snippit only used to convey the concept, not the actual practice ..

Of course that was before we had C#, and my processors only had 1k of RAM and we had to walk to work - up hill both ways......

MalcB | mailto:mboczekAT NOSPAMNOSPAMterraindustriesDOTcom | mboczekAT NOSPAMNOSPAMterraindustriesDOTcom

09/16/2008 8:32 PM

Its used in C++ to make sure that there is no operator overloading wierdness going on.

Interesting that your english representation "Zero the Value is not" reads like some kind of forth:

0 value !=

Because I'd read (0!=value) as "Zero is not equal to value", which is completely reasonable sounding to me.

But then that wouldn't sound so stupid would it? Instead, you do.

jamie | mailto:nospamthanksAT NOSPAMspecies dot org | nospamthanksAT NOSPAMspecies dot org

09/17/2008 9:34 AM

Jamie,

See http://en.wikipedia.org/wiki/Hyperbole

Chuck.

Chuck Jazdzewski | www.removingalldobut.com | chuckjAT NOSPAMmicrosoft dot com

09/18/2008 6:16 PM

Jamie,

To be less flippant, I decided to do an informal survey. I searched www.google.com for the phrase,

"Zero is not equal to the value"

The was exactly one hit,
www.freepatentsonline.com/5778070.html

(Dropping the "the" prior to value, as in your example, yields zero hits.)

Searching for the phrase,

"The value is not equal to zero"

renders 18,700+ hits.

I conclude that people who write English on the web don't agree with you that "zero is not equal to value" is "completely reasonable sounding" otherwise they would have used it more than once (and outside a patent application). 18,700:1 is too big to ignore even in a non-scientific poll.

See my subjects and objects response above that I gave to Ranty. It might make it more clear why this kind of result should be completely expected.

Chuck.

Chuck Jazdzewski | www.removingalldoubt.com | chuckjAT NOSPAMmicrosoft dot com

09/19/2008 11:11 AM

This is perfectly legal in C#:

int x = 1;

if ( (x=1) == 2 )
{
Console.WriteLine("x=" + x);
}

But this will incur a compiler error:

int x = 1;

if ( (1=x) == 2 )
{
Console.WriteLine("x=" + x);
}

Hence your core assertion that C# solves this problem is not true.

As well I could be a novice programmer who has learned it is good to add asserts:

bool fLaunchMissles = false;
System.Diagnostics.Debug.Assert((fLaunchMissles = true), "Don't let this happen ever!");

if (fLaunchMissles)
{
DoLaunchMissiles();
}

Ok, if you want to be responsible for this advice, its up to you. :)

09/29/2008 8:55 AM


Seems to me things are more readable if they follow normal patterns of speech.

"Ok bob, if it's false we fire up a form"

if (it == false)
form.Launch


The other way around is a yoda-ism at best.. "If false it is.. " and the ! operator is (imho) a bit like "if false we launch" .. not so bad, but contextual as to whether the shorthand is necessary



bob code | mailto:anonAT NOSPAMnospam dot net | anonAT NOSPAMnospam dot net

12/21/2008 6:11 AM

Hi,
I totally disagree. Since the left operand in any assignment has to be a "l-value", the following code won't compile:

int a;
if(2 = a)

and generates the "left operand must be l-value" error on compile time, saving you the hours, and even days to find the problematic area of the source that has been just happened while typing on that "electrically shocked keyboard"! :)

The problem is getting even hard to trace, when developing a "device driver"...

However, if you are talking about the left operand being either false or zero, I believe that you need to send the electric shock to them, since they didn't use the ! operator in the first place.

Mehdi Mousavi | http://mehdi.biz | mehdi_mousaviAT NOSPAMhotmail dot com

01/28/2009 5:23 AM

How about this code:
bool b;
...
if(b.ToString().Length > 4)
{
//false
}
else
{
//true
}

Is this a pet peave too?

MUster | mailto:jaynaland at gmail dot com | jaynaland at gmail dot com

Add New

Name

Email

Homepage

Security Word

Type in the security Word

Content (HTML not allowed)