Click here to Skip to main content
15,891,431 members
Articles / Programming Languages / C# 4.0
Tip/Trick

Which is better Constant [Comparison Operator] Variable Value or Variable Value [Comparison Operator] Constant? An introduction to Yoda Condition

Rate me:
Please Sign up or sign in to vote.
2.00/5 (1 vote)
30 May 2012CPOL2 min read 14.2K   4
In this tip we will figure out the importance of Yoda style in programming

Introduction

Many of us has the habit of writing the programming logic as follows

Case 1:

int a = 5;
if (a == 6){
    //do something
}

or Case 2:

bool x = false;
if (x == true){
    //do something
}

That means we are using equality comparison operator to compare the values.But, if by mistake we write like

Case 1:

int a = 5;
if (a = 6){
    //do something
}

or Case 2:

bool x = false;
if (x = true){
    //do something
}

Then the whole purpose of conditional checking will be wrong.

I do agree that for the first case, C# will give a compilation error Cannot implicitly convert type 'int' to 'bool'

while for the second case the it leaves away by giving an warning Assignment in conditional expression is always constant;did you mean to use == instead of = ?

The Yoda style

A better way to write code in that case will be in the Yoda style as below

Case 1:

int a = 5;
if (6 == a){
    //do something
}

or Case 2:

bool x = false;
if (true == x){
    //do something
}

Why?Because it reduces coding errors where we unintentionally mistyped the comparison operator == as a single =

Case 1:

int a = 5;
if (6 = a){
    //do something
}

or Case 2:

bool x = false;
if (true = x){
    //do something
}

C# will give compilation error in both the cases as The left-hand side of an assignment must be a variable, property or indexer

In simple words,we can't assign a value to a literal

Usage of this conditions style was popular on C/C++ where we could assign value to variable when typed = instead of ==

Does it really needed in C#?

Well from all the above experiments (atleast Case 1), we have seen that in C# expressions are not converted automatically to bool and henceforth this practice does not make much sence in C# parlance

However,the convention should be to always put the constant on the left hand side of the expression so that an error can be statically detected at compile time in the event of a typo e.g. = (assignment) was coded instead of the == (equality).

How IL interpretes?

To answer this question, we have developed a simple program as under

public bool ConstantLeft(int a)
     {
        return a == 1;
     }

    public bool ConstantRight(int a)
    {
        return 1 == a;
    }

When viewed in IL, we found the below for ConstantLeft() function

.method public hidebysig instance bool  ConstantLeft(int32 a) cil managed
{
  // Code size       10 (0xa)
  .maxstack  2
  .locals init ([0] bool CS$1$0000)
  IL_0000:  nop
  IL_0001:  ldarg.1
  IL_0002:  ldc.i4.1
  IL_0003:  ceq
  IL_0005:  stloc.0
  IL_0006:  br.s       IL_0008
  IL_0008:  ldloc.0
  IL_0009:  ret
} // end of method Class1::ConstantLeft

For ConstantRight() function, IL view is as under

.method public hidebysig instance bool  ConstantRight(int32 a) cil managed
{
  // Code size       10 (0xa)
  .maxstack  2
  .locals init ([0] bool CS$1$0000)
  IL_0000:  nop
  IL_0001:  ldc.i4.1
  IL_0002:  ldarg.1
  IL_0003:  ceq
  IL_0005:  stloc.0
  IL_0006:  br.s       IL_0008
  IL_0008:  ldloc.0
  IL_0009:  ret
} // end of method Class1::ConstantRight

The IL infers that, line numbers IL_0001 and IL_0002, they're just swapped but the order of the operands doesn't change the behavior of ceq at IL_0003.So apart from swapping, there was no change found.

Reference

What are yoda conditions?

Conclusion

Hope this little tip will be helpful. Comments and suggestions are welcome.

Thanks for reading.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
GeneralThoughts Pin
PIEBALDconsult31-May-12 3:50
mvePIEBALDconsult31-May-12 3:50 
Yoda style is pointless -- perhaps even a code smell. I was introduced to it back in the mid-90s, doing C in a company that had it in their coding standard, so I did it. But by the time I left that company, the newer developers weren't doing it and even the "guru" admitted that it was silly. I haven't used it since.

The main drawback is that it only applies when you need to compare an L-value and an R-value for equality, which is a pretty limited scope (and the scope is even more limited in C#). Hence, if a developer can remember to do it when it's applicable then he's aware enough of what he's doing not to make that mistake anyway. I'll allow that awareness of Yoda style may be of some help, but actually doing it isn't.

A better solution to the potential problem is to use a better compiler:

    if ( result = 5 )
....^
%CC-I-CONTROLASSIGN, In this statement, the assignment expression "result=5" is used as the controlling expression of an if, while o
r for statement.
at line number 13 in file MY$ROOT:[000000]AA.C;4
Description: A common user mistake is to accidentally use assignment operator "=" instead of the equality operator "==" in an expres
sion that controls a transfer. For example saying if (a = b) instead of if (a == b).  While using the assignment operator is valid,
it is often not what was intended.  When this message is enabled, the compiler will detect these cases at compile-time. This can oft
en avoid long debugging sessions needed to find the bug in the user's program.
User Action: Make sure that the assignment operator is what is expected.



And if your developers are ignoring warnings, then how are you going to get them to use Yoda style?


Furthermore, you must have a dedicated configuration management team to perform your test and production builds -- developers should not be doing that, so such potential bugs should not be getting through anyway.
GeneralOn a philosophical point, the language should meet our needs rather than force us to meet its. Pin
John Brett30-May-12 22:15
John Brett30-May-12 22:15 
Suggestion[My vote of 2] Not really needed, C# is not C PinPopular
verence30-May-12 3:55
verence30-May-12 3:55 
GeneralRe: [My vote of 2] Not really needed, C# is not C Pin
Klaus Luedenscheidt30-May-12 19:02
Klaus Luedenscheidt30-May-12 19:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.