编码“ if”的样式。陈述 [英] Coding style of "if" statements

查看:71
本文介绍了编码“ if”的样式。陈述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我一直在注意一些向后编写 if语句的程序员的风格。也就是说,在测试中,他们首先将常量值放在其后,然后将其测试中的变量放在第二位。例如,他们这样写:

Lately I've been noticing the style of some programmers who write "if" statements backwards. That is, in the test they put the constant value first and then the variable that they are testing second. So for example they write:

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

对我来说,这使得代码有些难以阅读。由于我们实际上是在谈论测试变量 bar的值,而不是测试所有等于 MY_CONSTANT的变量,因此我总是将变量放在第一位。它是一种不言而喻的语法。

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

无论如何,我看到有些程序员 ALWAYS 的执行顺序相反。此外,我仅在过去几年中注意到这一点。我从事C语言编程已有25年以上,直到最近4年左右,我才开始看到它。所以我的问题是:

Anyhow, I see that some programmers ALWAYS do this in the opposite order. Further, I've only noticed this in the past few years. I've been programming in C for over 25 years and I've not seen this until, say, about the last 4 years or so. So my question is:

人们这样做是有原因的吗?如果是的话,那是什么?这是某些语言或项目的通用标准,还是某些大学的教学标准?还是只是少数人试图与众不同?

Is there a reason people are doing this and if so what is it? Is this a common standard in some languages, or projects, or is it taught in some universities? or is that just a few people trying to be different?

推荐答案

这就是所谓的 Yoda风格(或 Yoda条件 或 Yoda表示法),并应防止您意外书写

This is called "Yoda-Style" (or "Yoda conditions" or "Yoda notation") and should prevent you from accidentally writing

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

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

将触发编译器错误。

该名称是由星号中不常见的扭曲句子构造派生的

The name is derived from the uncommon twisted sentence construction the Star Wars character Yoda is also using.

在我看来,使用 Yoda-Style会使对代码的理解更加困难,因为它违反了正常的句子构造规则。同样,代码质量检查器(或者如注释中提到的,甚至编译器本身)也应该抱怨这种分配,因此(恕我直言)没有充分的理由来混淆您的代码。

In my opinion using "Yoda-Style" makes understanding of code harder because it is against the normal sentence construction rules. Also code quality checker (or as mentioned in the comments maybe even the compiler itself) should complain about such assignments anyway, so that (imho) there is no good reason to obfuscate your code.

这篇关于编码“ if”的样式。陈述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆