Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the best practices: MethodReturnsBoolean == true/false OR true/false == MethodReturnsBoolean

I have been writing:

if(Class.HasSomething() == true/false) 
{
  // do somthing
}
else
{
  // do something else
}

but I've also seen people that do the opposite:

if(true/false == Class.HasSomething())
{
  // do somthing
}
else
{
  // do something else
}

Is there any advantage in doing one or the other in terms of performance and speed? I'm NOT talking about coding style here.

like image 897
Ray Cheng Avatar asked May 03 '12 15:05

Ray Cheng


People also ask

Is 1 equal to true in Python?

Python Booleans as Numbers Because True is equal to 1 and False is equal to 0 , adding Booleans together is a quick way to count the number of True values.

Is 0 considered false in Python?

Python assigns boolean values to values of other types. For numerical types like integers and floating-points, zero values are false and non-zero values are true. For strings, empty strings are false and non-empty strings are true.


2 Answers

They're both equivalent, but my preference is

if(Class.HasSomething())
{
  // do something
}
else
{
  // do something else
}

...for simplicity.

like image 97
MCattle Avatar answered Oct 05 '22 23:10

MCattle


Certain older-style C programmers prefer "Yoda Conditions", because if you accidentally use a single-equals sign instead, you'll get a compile time error about assigning to a constant:

if (true = Foo()) { ... }  /* Compile time error!  Stops typo-mistakes */
if (Foo() = true) { ... }  /* Will actually compile for certain Foo() */

Even though that mistake will no longer compile in C#, old habits die hard, and many programmers stick to the style developed in C.


Personally, I like the very simple form for True statements:

if (Foo()) { ... }  

But for False statements, I like an explicit comparison.
If I write the shorter !Foo(), it is easy to over-look the ! when reviewing code later.

if (false == Foo()) { ... }  /* Obvious intent */
if (!Foo())  { ... }         /* Easy to overlook or misunderstand */
like image 26
abelenky Avatar answered Oct 06 '22 01:10

abelenky