使用“get”的最佳实践是什么? 在方法名称中?

发布于 2024-07-08 12:18:58 字数 1447 浏览 11 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

七堇年 2024-07-15 12:18:59

只是一个简短的补充:另一个约定是布尔字段的 getters 以“is”而不是“get”为前缀,例如 bool isEnabled() { return enabled; } }

Just a short addendum: Another convention is for getters of Boolean fields to be prefixed with "is" instead of "get", e.g. bool isEnabled() { return enabled; }

九厘米的零° 2024-07-15 12:18:59

Objective C 2.0 也使用属性,使用相同的点语法。

在此之前,它对 getter 和 setter 使用了稍微不同的命名方案(当然,它仍然可以与属性一起使用,或者用于普通的旧属性)。

value = [obj attr];

[obj setAttr:value];

[obj getAttr:&value];

也就是说,get 的使用方式不同。 它不返回值,而是将结果存储在传入的变量中。

典型的 getter 与属性同名,setter 是以 set 为前缀的属性(按照 Java 的约定)。 这些约定由 KVO(键值观察)系统使用,因此应该遵守。

Objective C 2.0 also uses properties, using the same dot syntax.

Prior to that, it used a slightly different naming scheme for getters and setters (which, naturally, can still be used with properties, or for plain old attributes).

value = [obj attr];

[obj setAttr:value];

[obj getAttr:&value];

That is, get is used in a different way. It doesn't return a value, but stores the result in the passed in variable.

The typical getter has the same name as the attribute, the setter is the attribute prefixed by set (as per Java's convention). These conventions are used by the KVO (Key-Value Observation) system, so should be adhered to.

灯下孤影 2024-07-15 12:18:58

我个人喜欢以下规则:

  • 只要可以使用相应的 set 方法直接修改值,就使用 get 前缀
  • 在以下情况下删除 get 前缀该值是您无法直接设置为属性的值(即没有等效的 setXXX 方法)

第二种情况的基本原理是,如果该值实际上不是用户可设置的“属性”,那么它应该不需要一对 get/set 方法。 这意味着,如果遵循此约定并且您看到 getXXX 方法,则可以假设也存在 setXXX 方法。

示例:

  • String.length() - 由于字符串是不可变的,长度是只读值
  • ArrayList.size() - 添加或删除元素时大小会发生变化,但是你不能直接设置它

I personally like the following rule:

  • Use the get prefix whenever the value is directly modifiable with a corresponding set method
  • Drop the get prefix in situations where the value is something you can't set directly as a property (i.e. there is no equivalent setXXX method)

The rationale for the second case is that if the value isn't really a user-settable "property" as such, then it shouldn't need a get/set pair of methods. An implication is that if this convention is followed and you see a getXXX method, you can assume the existence of a setXXX method as well.

Examples:

  • String.length() - since strings are immutable, length is a read-only value
  • ArrayList.size() - size changes when elements are added or removed, but you can't set it directly
野却迷人 2024-07-15 12:18:58

这归结为语义。 是的,C# 具有“属性”,可以为您提供获取/设置“方法”存根...但是 .NET Framework 中以“Get”开头的函数(...“方法”...)应该可以提供线索开发人员意识到某些操作发生的唯一目的是获得某些结果。

您可能会认为这很奇怪,并说“为什么不直接使用返回类型来提示人们呢?”,答案很简单。 考虑以下方法:

public Person CreatePerson(string firstName, string lastName) {...}

仅通过该方法的名称,您就可以推测将涉及数据库活动,然后将返回一个新创建的“人”。

但是,这个怎么样:

public Person GetPerson(string firstName, string lastName) {...}

仅通过该方法的名称,您就可以假设正在从数据库中 100%“安全”地检索人员。

您永远不会多次调用“CreatePerson”...但是您应该始终安全地调用“GetPerson”。 (它不应该影响应用程序的“状态”)。

It comes down to semantics. Yes, C# has "properties" which give you a get/set 'method' stub... but functions (..."methods"...) in the .NET Framework that start with "Get" is supposed to clue the developer into the fact that some operation is happening for the sole purpose of getting some results.

You may think that's odd and say "why not just use the return type to clue people in?", and the answer is simple. Think of the following methods:

public Person CreatePerson(string firstName, string lastName) {...}

Just by that method's name, you can probably figure that there will be database activity involved, and then a newly created "person" will be returned.

but, what about this:

public Person GetPerson(string firstName, string lastName) {...}

Just by that method's name, you can probably assume that a 100% "Safe" retrieval of a person from a database is being done.

You would never call the "CreatePerson" multiple times... but you should feel safe to call "GetPerson" all the time. (it should not affect the 'state' of the application).

霓裳挽歌倾城醉 2024-07-15 12:18:58

Java 中的“get”和“set”前缀对最初用作表示 java bean 的约定。 后来,它只是一种封装约定,因为与 C# 不同,Java 没有适当的属性。

"get" and "set" prefix pair in Java is used originally as a convention to denote java bean. Later, it become just an encapsulation convention, since Java, unlike C# doesn't have proper properties.

漫漫岁月 2024-07-15 12:18:58

Java 中的最佳实践是使用属性的 get 和 set 前缀。

框架、标签库等将查找具有这些前缀的方法并将它们用作属性。

所以,如果你有一个像这样的java类......

public class User{
    private String name;
    public String getName(){ return name;}
    public void setName(String name){ this.name = name; }
}

带有struts-tags(或任何其他基于ognl的标签库),你将使用user.name访问name属性。

Spring 框架也在 xml 配置文件中使用此约定。

The best practice in Java is to use the get and set prefixes for properties.

Frameworks, tag libraries, etc will look for methods with those prefixes and use them as properties.

So, if you have a java class like this...

public class User{
    private String name;
    public String getName(){ return name;}
    public void setName(String name){ this.name = name; }
}

.. with struts-tags (or any other ognl based tag library) you will access the name property with user.name.

The Spring framework also uses this convention in the xml configuration files.

在巴黎塔顶看东京樱花 2024-07-15 12:18:58

13年后,我相信这个问题值得重新审视。 当然,随着时间的推移,有很多 stackoverflow 问答(甚至这里有一些很好的答案)、文章和博客文章得出了相同的结论,但最后,我认为,我们从 Brian Goetz 本人:

“JavaBeans 命名约定*是一个有点不幸的故事,”他继续说道。 “对于通用开发来说,这是一个糟糕的约定。 这是在可视化编辑器中命名可视化组件的一个相当有针对性的约定,您可以将按钮和标签以及类似的东西拖放到画布上,并且您可以编辑有关前景色和字体等的属性表。有你吗,这可以通过反思发现。”

Goetz 解释说,命名约定是构建这些 UI 组件的好方法——事实证明,这并不是一个关键的 Java 用例。 “然而,不知何故,我们继续采用这种命名约定,尽管它与大多数业务领域对象的匹配度很差。”

https://blogs.oracle.com/javamagazine/java -architects-loom-panama-valhalla#anchor_4

*  – 基本上,所涉及的 getX/setX 约定

13 years later, I believe this question deserves a revisit. Surely, over the time there were a lot of stackoverflow Q&A-s (even some good answers here), articles and blog posts that amounted to the same conclusion, but finally, I think, we get a rather straightforward answer from Brian Goetz himself:

“The JavaBeans naming convention* is a little bit of an unfortunate story,” he continues. “It’s a terrible convention for general-purpose development. It was a fairly well-targeted convention for naming visual components in a visual editor, where you were dragging and dropping buttons and labels and things like that onto a canvas, and you had property sheets that you could edit about foreground color and fonts and what have you, which could be discovered reflectively.”

Goetz explains that the naming convention was great way building those UI components—which turns out to not have been a key Java use-case. “And yet, somehow, we continued with that naming convention, even though it’s such a poor match for most business domain objects.”

https://blogs.oracle.com/javamagazine/java-architects-loom-panama-valhalla#anchor_4

* – basically, the getX/setX convention in question

勿挽旧人 2024-07-15 12:18:58

Java(尚)不支持属性。 getter 和 setter 是解决这个问题的一个障碍。 其他语言(包括 C#)支持属性,您应该使用这些属性。 这也不仅仅是一个“最佳实践”:C# 中的序列化将依赖于属性,而不是 getter 和 getter。 设置器,因此如果您需要序列化类,不使用属性可能会在将来导致各种问题。

属性的优点是它们使代码更具可读性。 像

obj.setX(10);

在Java中一样,

obj.X = 10;

在幕后,X是一个方法,而不是一个变量,因此可以执行脏输入检查等。

Java doesn't (yet) support properties. Getters and setters are a bodge to get around this. Other languages - including C# - support properties and you should use these instead. This isn't just a "best practice" thing either: serialization in C# will rely on properties, not getters & setters, so not using properties could lead to all sorts of problems in the future if you need to serialize your classes.

The advantage to properties is that they make the code more readable. Something like

obj.setX(10);

in Java, becomes

obj.X = 10;

Yet behind the scenes, X is a method, rather than being a variable and so can perform dirty input checking etc.

墨落画卷 2024-07-15 12:18:58

过去的情况确实如此,API 经常公开不带 get 前缀的只读属性:String.length() 甚至较新的 Buffer.capacity() 是合理的示例。

这样做的好处是,涉及的绒毛更少。 缺点是任何试图根据约定自动确定属性的东西都不会发现它们。 就我个人而言,我倾向于在包含前缀方面犯错误。

当然,在 C# 中,这基本上是无关紧要的,因为无论如何都有“真实”属性:)

It certainly used to be the case that APIs often exposed read-only properties without the get prefix: String.length() and even the newer Buffer.capacity() being reasonable examples.

The upside of this is that there's less fluff involved. The downside is that anything which tries to determine properties automatically based on the conventions won't discover them. Personally I tend to err on the side of including the prefix.

Of course, in C# it's mostly irrelevant as there are "real" properties anyway :)

回忆那么伤 2024-07-15 12:18:58

这取决于。 即使在没有属性的语言中,它通常也是冗余信息。

在 C++ 中,通常提供 Attr() 函数的两个重载,而不是 getAttr()/setAttr() 对:
无效 Attr(Foo f); // 设置器
Foo Attr(); // getter

在 Java 中,通常的做法是在 get/set 前加上前缀。
我不得不说,最好的做法是遵循您的语言的标准。 在 Java 中,人们希望看到 get/set 前缀,因此省略它们可能会让人们感到困惑,即使它们并不是绝对必要的。

It depends. It is often redundant information, even in languages without properties.

In C++, instead of a getAttr()/setAttr() pair, it is common to provide two overloads of an Attr() function:
void Attr(Foo f); // The setter
Foo Attr(); // The getter

In Java, it is common practice to prefix get/set.
I'll have to say the best practice is to go with what's standard in your language. In Java, people expect to see get/set prefixes, so omitting them might confuse people, even though they're not strictly necessary.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文