AlumnForce / coding-conventions

[DEPRECATED] Style guide & coding conventions for AlumnForce projects
Creative Commons Attribution 4.0 International
11 stars 2 forks source link

Add Yoda Conditions style #6

Closed mrDlef closed 6 years ago

mrDlef commented 6 years ago

Yoda Conditions

When doing logical comparisons involving variables, always put the variable on the right side and put constants, literals, or function calls on the left side. If neither side is a variable, the order is not important. (In computer science terms, in comparisons always try to put l-values on the right and r-values on the left.)

if (true == $theForce) {
    $victorious = youWill($be);
}

In the above example, if you omit an equals sign (admit it, it happens even to the most seasoned of us), you’ll get a parse error, because you can’t assign to a constant like true. If the statement were the other way around ($theTorce = true), the assignment would be perfectly valid, returning 1, causing the if statement to evaluate to true, and you could be chasing that bug for a while.

A little bizarre, it is, to read. Get used to it, you will.

This applies to ==, !=, ===, and !==. Yoda conditions for <, >, <= or >= are significantly more difficult to read and are best avoided.

geoffroy-aubry commented 6 years ago
geoffroy-aubry commented 6 years ago

Do not use Yoda:

geoffroy-aubry commented 6 years ago

Do not use Yoda:

geoffroy-aubry commented 6 years ago

The Clean Coder: « I dislike any statement in code that causes the reader to do a double-take. Code that protects the author at the expense of the reader is flawed code. »

geoffroy-aubry commented 6 years ago

Even if I vote against, I thank you for your proposal :)

nunomaduro commented 6 years ago

Great proposal! This thumbs vote format is really cool. For this proposal I vote against tho.

wodzy commented 6 years ago

I think this makes the code harder to read. I vote against too.

mrDlef commented 6 years ago

Here are some good resources about that:

As we don't have enough unit tests and linters for our legacy code I thought it would be a good way to be sure of the behavior of a condition. Cool to discuss on that anyway.