如果您使用 getter 和 setter,您应该如何命名私有成员变量?
As kind of a follow up to this question about prefixes, I agree with most people on the thread that prefixes are bad. But what about if you are using getters and setters? Then you need to differeniate the publicly accessible getter name from the privately stored variable. I normally just use an underscore, but is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我喜欢写“this.x = x”。 我很清楚。 另外,当使用 Eclipse 时,您可以让它以这种方式自动生成 getter/setter。
I like writing "this.x = x". It's very clear to me. Plus, when using Eclipse, you can have it automatically generate your getters/setters this way.
这是一个完全主观的问题。 没有“更好”的方法。
一种方法是:
另一种方法是:
都不是正确答案。 每种风格都有优点和缺点。 选择您最喜欢的一种并持续应用。
This is a completely subjective question. There is no "better" way.
One way is:
Another is:
Neither is the right answer. Each has style advantages and disadvantages. Pick the one you like best and apply it consistently.
有多少程序员就有多少种不同的方法,但一些更流行的方法包括(对于属性
Foo
):There are almost as many different ways of doing this as there are programmers doing this, but some of the more popular ways include (for a property
Foo
):在区分大小写的语言中,我只使用:
否则我会使用下划线
In a case sensitive language I just use:
Otherwise I would use an underscore
在java中有this.foo,在python中有self.foo,其他语言也有类似的东西,所以当我已经可以使用语言构造时,我认为不需要以特殊的方式命名某些东西。 在相同的上下文中,好的 IDE 和编辑器可以理解成员变量并给它们一个特殊的突出显示,因此您可以真正看到它而无需使用特殊名称。
In java there is this.foo in python there is self.foo and other languages have similar things, so I don't see a need for naming something in a special way, when I can already use a language construct. In the same context good IDEs and editors understand member variables and give them a special highlight, so you can really see it w/o using special names.
正如其他人提到的,我喜欢在字段前加上下划线。
我认为这超出了个人偏好(正如大卫·阿诺在这篇文章中所说)。 我认为这样做有一些真正客观的原因:
(这些约定适用于 Java,但其他语言也存在类似的约定)
这些东西看起来很小,但它们的流行确实让我在编码时的生活变得更轻松。
I like prefixing fields with an underscore, as others have mentioned.
I think this goes beyond straight personal preference though (as David Arno said in this thread). I think there's some real objective reasons for doing this:
(These conventions are for Java, but similar ones exist for other languages)
These things seems small but their prevalence definitely makes my life easier when I'm coding.