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.
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.
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.
They're both equivalent, but my preference is
if(Class.HasSomething())
{
// do something
}
else
{
// do something else
}
...for simplicity.
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 */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With