The coding style of the if statements

Recently, I have noticed the style of some programmers who write "if" statements back. That is, in the test, they first set a constant value, and then the variable that they test the second. So, for example, they write:

bar = foo(); if (MY_CONSTANT == bar) { /* then do something */ } 

For me, this makes the code somewhat difficult to read. Since we are really talking about testing the value of the variable "bar", and not all the variables that are equal to "MY_CONSTANT", I always put this variable in the first place. This is a kind of unspoken grammar.

In any case, I see that some programmers ALWAYS do this in the reverse order. In addition, I only noticed this in the last few years. I have been programming in C for over 25 years, and I have not seen this until, say, the last 4 years or so. So my question is:

Is there a reason people do this, and if so, what is it? Is this a generally accepted standard in some languages ​​or projects, or is it taught at some universities? or is it just a few people trying to be different?

+6
source share
2 answers

This is called the “Yoda Style” (or “Yoda Conditions” or “Yoda Notation”) and should prevent you from accidentally writing

 if (bar = MY_CONSTANT) { /* then do something */ } 

because

 if (MY_CONSTANT = bar) { /* then do something */ } 

will result in a compiler error.

The name comes from the unusual design of the twisted sentence, which also uses the character of Star Wars Yoda.

In my opinion, the use of "Yoda-style" complicates the understanding of the code, because it contradicts the normal rules for constructing sentences. Also, checking the quality of the code (or, as mentioned in the comments, perhaps even the compiler itself) should somehow complain about such assignments, so (imho) there is no good reason for confusing your code.

+18
source

It's a bit of a best practice that someone thought was best 15 years ago or so. The perceived benefit was that it would prevent the random execution of tasks instead of comparisons.

It was questionable back than, this is a 100% contentious issue nowadays, since any compiler worth using will warn about assignment to the branch operator, but hordes of lemmings are still a copy of the best practice , without even thinking what it means or what it is for .

+7
source

All Articles