473,396 Members | 1,847 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Coding Standards, why if ( boolVar ) over if ( boolVar == true )

I've been flipping through various coding standards documents for C#/.NET
and all of them say to use:

if ( boolVar ) {...} instead of if ( boolVar == true ) {...}

For the life of my I can't figure out why. If anything, I would guess the
opposite would be better to use since the ! operator is so hard to read.

Upon quick glance,

if ( boolVar == false ) is easier to understand than if ( !boolVar )

Anybody have some more concrete reasons why one is preferred over the other
aside from one being less typing.

Thanks,
-A

Nov 16 '05 #1
16 1440
Alfred:

This can degenerate into a holy war. In general, I would recommend keeping
it as simple as possible. Think about looking at this code 3 months from
now, at 2:00 AM under a deadline after working 15 hour days for 2 months
straight.

8-)... Been there...

John
"Alfred Taylor" <om***@R-E-M-O-V-Eyahoo.com> wrote in message
news:Ou**************@tk2msftngp13.phx.gbl...
I've been flipping through various coding standards documents for C#/.NET
and all of them say to use:

if ( boolVar ) {...} instead of if ( boolVar == true ) {...}

For the life of my I can't figure out why. If anything, I would guess the
opposite would be better to use since the ! operator is so hard to read.

Upon quick glance,

if ( boolVar == false ) is easier to understand than if ( !boolVar )

Anybody have some more concrete reasons why one is preferred over the other aside from one being less typing.

Thanks,
-A

Nov 16 '05 #2
This is where I invoke my #1 rule of programming style. :)

"Code written to a mediocre standard is better than brilliant code that
is not standard."

or, stated another way:

"If everyone else is doing it a standard way, your clever solution is
by definition no longer clever, unless it offers some stunning
advantage over the standard."

If everyone in the industry were writing

If (boolVar == true)

and I were to write instead

if (boolVar)

claiming that it was "better" because I had to type fewer characters, I
would not blame my colleagues if they were to give me the wedgie to end
all wedgies and tossed me out on the street. Every time they were to
read my code they would have to mentally stop and think about what I
was doing.

The reverse is also true.

Almost every C / C++ / Java / C# programmer out there writes

if (boolVar)

and

if (!boolVar)

that fact, in and of itself, makes the alternative syntax "less
readable".
From personal experience, I can say that reading


if (boolVar == false)

is like a speed bump for me. I've been reading C for 20 years and I'm
used to the standard. It has, in effect, become "more readable" for me.

Nov 16 '05 #3
Hi Alfred,

"Alfred Taylor" <om***@R-E-M-O-V-Eyahoo.com> wrote in message
news:Ou**************@tk2msftngp13.phx.gbl...
I've been flipping through various coding standards documents for C#/.NET
and all of them say to use:

if ( boolVar ) {...} instead of if ( boolVar == true ) {...}

For the life of my I can't figure out why. If anything, I would guess the
opposite would be better to use since the ! operator is so hard to read.

Upon quick glance,

if ( boolVar == false ) is easier to understand than if ( !boolVar )

Anybody have some more concrete reasons why one is preferred over the other aside from one being less typing.


In short, it prevents syntax errors from becoming logical errors. It's
not unusual, especially for people who haven't used C-variant languages in
the past, to accidentally use the assignment operator (=) instead of the
equality operator (==). Consider this C# code:

int i = 0;
...
if (i = 3) {...}

The above code would be flagged as a compile-time error because the
assignment operator (=) returns the value assigned, which in this case is 3,
which is not a boolean value. On the other hand, if you do this:

bool boolVar = false;
...
if (boolVar = true) {...}

The above code will not cause a compile time error, even though it's
probably not what was intended. The assignment operator (=) returns the
value assigned, which in this case is true, which *is* a boolean value.

If you never use "== true" or "== false" the mistake can be avoided.

Regards,
Daniel
Nov 16 '05 #4
For those who found my preceding reply utterly unconvincing :) I offer
the following:

The problem with Alfred's original sample was the name of the variable.

Programmers are _supposed_ to name their boolean variables to express
the condition that they represent. In that situation, I find this:

if (isADuplexPrintJob)

much more readable than this:

if (isADuplexPrintJob == true)

because in the first example I'm expressing something in terms of my
problem domain ("if this is a duplex print job then I want to...")
whereas in the second example I have to remember that this is a boolean
variable, and that it's either true or false, and that "true" means
that it is a duplex print job.

One encourages me to think about my problem; the other notation
encourages me to think about what's going on inside the machine.

Of course, if you name your boolean variable "flag", or something
equally opaque, then this argument doesn't hold water. But then, we
would never do _that_, would we...? :)

Nov 16 '05 #5
Oooh! Good one!

Nov 16 '05 #6

"Bruce Wood" <br*******@canada.com> wrote in message
news:11**********************@c13g2000cwb.googlegr oups.com...
From personal experience, I can say that reading


if (boolVar == false)

is like a speed bump for me. I've been reading C for 20 years and I'm
used to the standard. It has, in effect, become "more readable" for me.


That's a good point. I know the times I've run across that style of code,
I've had to pause momentarily to "recompose" myself. ;)
-A

Nov 16 '05 #7
Thanks Daniel. That is definitely a very legitimate reason for avoiding "==
true" and "== false".

-A

"Daniel Pratt" <ko******************@hotmail.com> wrote in message
news:%2****************@TK2MSFTNGP14.phx.gbl...
Hi Alfred,

"Alfred Taylor" <om***@R-E-M-O-V-Eyahoo.com> wrote in message
news:Ou**************@tk2msftngp13.phx.gbl...
I've been flipping through various coding standards documents for C#/.NET and all of them say to use:

if ( boolVar ) {...} instead of if ( boolVar == true ) {...}

For the life of my I can't figure out why. If anything, I would guess the opposite would be better to use since the ! operator is so hard to read.

Upon quick glance,

if ( boolVar == false ) is easier to understand than if ( !boolVar )

Anybody have some more concrete reasons why one is preferred over the other
aside from one being less typing.


In short, it prevents syntax errors from becoming logical errors. It's
not unusual, especially for people who haven't used C-variant languages in
the past, to accidentally use the assignment operator (=) instead of the
equality operator (==). Consider this C# code:

int i = 0;
...
if (i = 3) {...}

The above code would be flagged as a compile-time error because the
assignment operator (=) returns the value assigned, which in this case is

3, which is not a boolean value. On the other hand, if you do this:

bool boolVar = false;
...
if (boolVar = true) {...}

The above code will not cause a compile time error, even though it's
probably not what was intended. The assignment operator (=) returns the
value assigned, which in this case is true, which *is* a boolean value.

If you never use "== true" or "== false" the mistake can be avoided.

Regards,
Daniel


Nov 16 '05 #8
Hi, Alfred,
if ( boolVar ) {...} instead of if ( boolVar == true ) {...}


Because it's redundant. One might as well ask, why

if ( boolVar == true ) instead of if ( (boolVar == true) == true)
Peace,
--Carl

Nov 16 '05 #9
100% correct.

Also, as I was reading this thread, I kept on thinking that in

if(something) {...}
you are looking at the value of 'something', whereas in

if(something==true) {...}
you are technically speaking looking at the result of a comparison
between 'something' and a value ('true'). Granted the net effect is the
same, but, technically speaking, there are differences. And if
something was not a boolean, the comparison might actually open a whole
can of worms (but that would be a different playground, right?).

Still, the reason illustrated by Daniel above is probably the best
reason to avoid if(something==true).

F.O.R.

Nov 16 '05 #10

"Bruce Wood" <br*******@canada.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
For those who found my preceding reply utterly unconvincing :) I offer
the following:

The problem with Alfred's original sample was the name of the variable.


Fair enough. ;)

-A

Nov 16 '05 #11
Incidentally (although I'm sure that this _will_ cause a holy war), I
apply the same reasoning to curly braces and all other manner of code
formatting: if I start work at a shop that formats their code a certain
way, and I insist upon continuing to do it "my way" because my way is
"better," then I am an idiot.

It doesn't matter how stupid "their way" of formatting code looks to
me. If everyone else in the shop is used to that, then that is what is
"more readable" and it is what I should be doing, too.

My dream shop would have an automated code formatter that would just
mash everyone's code and make it look the same every time it was
checked into the library. Visual Studio's "Edit->Advanced->Format
Selection" operation is your friend! Productivity wouldn't jump, but it
would improve.

I read stories of programmers (during the big boom, when we could get
away with anything, including bringing pets to work) insisting on
writing formatters / deformatters so that they could transform others'
code into "their" style, code in "their" style, and then transform the
code back to the group standards. I just shake my head in wonder at
such nonsense.

Nov 16 '05 #12
As a quick comment. I have a pet hate against this minimal typing when
it comes to string comparisons. Does anybody actually find this
readable ?!:

if ( !strcmp( string1, string2 ) )
{
// Strings match
}
else
{
// Strings dont match
}
I've gotten into the habit of putting the fixed value on the
left-hand-side. It takes a bit of getting used to, but as a consistent
approach I use this across the board, regardless of type.

if ( true == bValue )
{
}

if ( 0 == strcmp( string1, string2 ) )
{

}
etc..
etc..
Rich
Bruce Wood wrote:
Incidentally (although I'm sure that this _will_ cause a holy war), I
apply the same reasoning to curly braces and all other manner of code
formatting: if I start work at a shop that formats their code a certain way, and I insist upon continuing to do it "my way" because my way is
"better," then I am an idiot.

It doesn't matter how stupid "their way" of formatting code looks to
me. If everyone else in the shop is used to that, then that is what is "more readable" and it is what I should be doing, too.

My dream shop would have an automated code formatter that would just
mash everyone's code and make it look the same every time it was
checked into the library. Visual Studio's "Edit->Advanced->Format
Selection" operation is your friend! Productivity wouldn't jump, but it would improve.

I read stories of programmers (during the big boom, when we could get
away with anything, including bringing pets to work) insisting on
writing formatters / deformatters so that they could transform others' code into "their" style, code in "their" style, and then transform the code back to the group standards. I just shake my head in wonder at
such nonsense.


Nov 16 '05 #13
On 3 Feb 2005 02:16:07 -0800, "RichS"
<ri****************@surfcontrol.com> wrote:
I've gotten into the habit of putting the fixed value on the
left-hand-side. It takes a bit of getting used to, but as a consistent
approach I use this across the board, regardless of type.


Argh, I absolutely hate that. Mathematical tradition always puts
variables on the left and constants on the right of a comparison, and
that's also the natural way to read a comparison. One of the best
things about C# as compared to C++ is that there's no auto-conversion
of everything to boolean, so you no longer have to invert comparisons
to prevent typo bugs...
--
http://www.kynosarges.de
Nov 16 '05 #14
In article <11*********************@l41g2000cwc.googlegroups. com>,
ri****************@surfcontrol.com says...
As a quick comment. I have a pet hate against this minimal typing when
it comes to string comparisons. Does anybody actually find this
readable ?!:

if ( !strcmp( string1, string2 ) )
{
// Strings match
}
else
{
// Strings dont match
}

This is a different issue altogether. strcmp does not actually return
boolean value. So, although the above will still work, it is
technically incorrect because the other possible return values are
negative or positive numbers denoting which string is "greater"
alphabetically, rather than true or false.

Above should have been
if(strcmp(str1,str2)==0)
//stings match

I've gotten into the habit of putting the fixed value on the
left-hand-side. It takes a bit of getting used to, but as a consistent
approach I use this across the board, regardless of type.

if ( true == bValue )


This is uncessessary extra bit of coding imo. Good C/Java/C#
programmers should be able to read

if(bValue)

happily and not dismiss the ! operand as "hard to read" e.g.

if(!bValue).

Daniel has already given a very good example as to why using

if(bvalue==true)

is a not a good practice and

if(true==bValue)

is just a workaround, imo, for those not confident enough to read pure
C/Java/etc syntax.

Just my 2p worth.

Cheers,

Paul.
Nov 16 '05 #15
>
int i = 0;
...
if (i = 3) {...}


In good old days of C and C++ this would not have been flagged as a compile
time error which got quite a few people into habit of writing the condition
with constant on the left had side like : if ( 3 == i) This would trap the
missed equal to sign (if (3 = i)) as a compiler error !!
Nov 16 '05 #16
I never liked the

if (!strcmp(string1, string2))

convention in C. It just struck me as sloppy: strcmp returns a
tri-state value, not a dual-state value, so using ! always struck me as
a cheap trick. I always preferred to code

if (strcmp(string1, string2) == 0)

in order to highlight the fact that it could be zero, less than zero,
or greater than zero. As GingerDeafMan points out, thanks to Anders
Hejlsberg and team, C# doesn't allow you to treat integers as booleans,
so now everyone has to do it my way. :)

Of course, those few times when I was in a shop that had standardized
on testing strcmp results using the ! operator, I had to hold my nose
and adapt.... :)

Nov 16 '05 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: ganesan | last post by:
Hi Guys, Could any one knows the best coding standards styles(with variable declarations for c#) . and if any links or site with the best coding standards for .NET send me those links regards...
4
by: dotNetDave | last post by:
About three weeks ago I released the first .NET coding standards book titled "VSDN Tips & Tricks .NET Coding Standards". Here is what the famous author/ speaker Deborah Kurata says about it: ...
5
by: db2sysc | last post by:
ALl. Is it possible to get MS ACCESS CODING STANDARDS? TIA
144
by: Natt Serrasalmus | last post by:
After years of operating without any coding standards whatsoever, the company that I recently started working for has decided that it might be a good idea to have some. I'm involved in this...
50
by: Konrad Palczynski | last post by:
I am looking for tool to validate conformity to defined coding standard. I have already found Parasoft's C++ Test, but it is quite expensive. Is there any Open Source alternative? I do not need...
7
by: Robert Seacord | last post by:
The CERT/CC has just deployed a new web site dedicated to developing secure coding standards for the C programming language, C++, and eventually other programming language. We have already...
3
by: editormt | last post by:
A recent poll asked if programming standards are used by development organisations... and if they are controlled. None: 20% Yes, but without control: 49% Yes, with control: 31% Participants:...
0
by: pat | last post by:
CodeCheck Coding Standard's Support As a free service to our customers we offer support in developing "rule-files" for automating corporate coding standards. If you have a coding standard that...
19
by: auratius | last post by:
http://www.auratius.co.za/CSharpCodingStandards.html Complete CSharp Coding Standards 1. Naming Conventions and Styles 2. Coding Practices 3. Project Settings and Project Structure 4....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.