命名变量后他们的类型是不好的做法吗? [英] Is naming variables after their type a bad practice?

查看:150
本文介绍了命名变量后他们的类型是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编程C ++使用下划线命名风格(与驼峰情况相反),它也被STL和boost使用。但是,由于类型和变量/函数都被命名为全部小写,如下的成员变量声明将导致编译器错误(或至少麻烦):

I'm programming C++ using the underscore naming style (as opposed to camel case) which is also used by the STL and boost. However, since both types and variables/functions are named all lower case, a member variable declaration as follows will lead to compiler errors (or at least trouble):

position position;

成员变量名为 position ,类型为 / em>。我不知道如何命名它:它通常是一个位置,但它也是的位置的对象。在骆驼的情况下,这将是编译器很好:

A member variable named position which is of type position. I don't know how else to name it: It's generally a position, but it is also the position of the object. In camel case, this would be fine with the compiler:

Position position;

但在C ++中会导致问题。我不想切换到驼峰的情况下,使用匈牙利记法或添加一个尾随下划线,因此,我想知道:是一个好习惯,一个成员类似一个类型命名吗?

But in C++ it causes problems. I don't want to switch to camel case, use Hungarian notation or add a trailing underscore because of that, so I'm wondering: Is it a good practice to name a member like a type anyways?

在C中,使用隐藏的单字母变量是很常见的:

In C, it is pretty common to use cryptic one-letter variables for this:

int i;

但我发现有一点,好,隐蔽:

But I find that a bit, well, cryptic:

position p;

有没有可以使用的变量命名规则来避免这种情况?

Are there any rules of thumb for variable naming I can use to avoid this?

如果你需要一些工作,我的代码中还有更多的例子:

There are more examples in my code if you need something to work on:

mouse_over(entity entity) // Returns true if the mouse is over the entity

manager &manager; // A reference to the framework's manager

audio audio; // The audio subsystem

编辑

我很想知道Bjarne Stroustrup自己是否有关于这个问题的话。显然,他没有,但他建议编码约定,将解决我的编译器问题:

I was curious to see if Bjarne Stroustrup himself has something to say on this issue. Apparently, he hasn't, but he suggests coding conventions that would work around my compiler problems:


例如,大写非标准库user-

For example, capitalize nonstandard library user-defined types and start nontypes with a lowercase letter

这将与STL和boost一致,所以我可以使用它。然而,大多数人同意这个命名应该避免,不管它是否编译。 Stroustrup:

That'd be consistent with STL and boost, so I might use that. However, most of you agree that this naming should be avoided whether it compiles or not. So does Stroustrup:


选择只有大小写不同的名称是不明智的。

it is unwise to choose names that differ only by capitalization.


推荐答案

局部含义很少是类型的一个很好的唯一全局描述:

The local meaning is rarely a good unique global description of the type:

cartesian_point_2d position;  // rectangular, not polar coordinates
mouse_over(ui_entity entity); // not a business layer entity
xyz_manager& manager;         // what's a manager without something to manage?
audio_system audio;

这篇关于命名变量后他们的类型是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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