Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any good reason to write things "backwards", e.g.: if ("some_text" == var_name)?

I was doing a project in groups of 4 people, using C#.NET. While I naturally wrote down something like: if (var_name == "some_text"), one of the group members strongly insisted to change that line into if ("some_text" == var_name) and claim "it's a better programming practice" that she learned from some sensor programmer. No one in our group, not even herself, understood what's the motivation behind this besides it feels more awkward. Is this a better practice or it's just another urban myth?

like image 703
user1032613 Avatar asked Sep 25 '12 20:09

user1032613


4 Answers

There's no good reason for this in C#.

In C you can inadvertently forget one of the = signs, and C allows this:

if (x = 5)

Which will compile and always return either true or false (true if the variable was set to any non-zero value, false if it was zero). This was a common source of errors, so writing if (5 == x) prevents this as the C compiler would complain if you ommitted one of the = signs.

C# however does NOT allow assignment to be treated as a boolean condition, and thus its impossible to make this mistake, so the suggestion is pointless. I'd recommend sticking to the more natural "if x equals 5" style.

like image 78
Andy Avatar answered Oct 30 '22 22:10

Andy


Yes, I am not big fan of it.. But there is.. If you mistakenly would use operator assign (=) instead of compare it will not compile and/or it will immediately crash. At least in "common" programming languages ;-)

This web tells little bit more about it - http://united-coders.com/christian-harms/what-are-yoda-conditions/

like image 28
korCZis Avatar answered Oct 31 '22 00:10

korCZis


I started doing that in college when I took my first C++ class in an effort to not accidentally assign a value I was trying to check against, and it's just always followed me. However, when I use C#, I tend to do:

if (var_name.Equals("some_text"))

Not only does this prevent the accidental assignment, but to me, visually, seeing the Equals() is much more understanding than seeing a ==. Just my two cents.

like image 36
PiousVenom Avatar answered Oct 31 '22 00:10

PiousVenom


I was taught to write it backwards when I was taking an intro to programming course in college. We were using C++, and as other answers said, it had a difference in C++.

like image 42
user1704124 Avatar answered Oct 31 '22 00:10

user1704124