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

时间:2022-11-28 08:44:55

I've noticed in many places in Java (C# included), that many "getter" methods are prefixed with "get" while many other aren't. I never noticed any kind of pattern Sun seems to be following. What are some guidelines or rules for using "get" in getter method names?

我已经注意到Java中的很多地方(包括C#),许多“getter”方法都以“get”为前缀,而其他许多方法则没有。我从未注意到Sun似乎遵循的任何模式。在getter方法名称中使用“get”有哪些指导或规则?

9 个解决方案

#1


5  

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.

它归结为语义。是的,C#有“属性”,它为你提供了一个get / set'方法'存根......但.NET Framework中以“Get”开头的函数(...“methods”...)应该提示开发人员认为某些操作正在发生,其唯一目的是获得一些结果。

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.

只需使用该方法的名称,您就可以假设正在对数据库中的人进行100%“安全”检索。

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).

你永远不会多次打电话给“CreatePerson”......但是你应该总是安全地打电话给“GetPerson”。 (它不应该影响应用程序的“状态”)。

#2


4  

"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.

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

#3


4  

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

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

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...

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

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.

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

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

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

#4


2  

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.

Java(尚未)支持属性。吸气剂和二传手是一个可以解决这个问题的小屋。其他语言 - 包括C# - 支持属性,您应该使用它们。这不仅仅是“最佳实践”的事情:C#中的序列化将依赖于属性,而不是依赖于getter和setter,因此如果您需要序列化类,不使用属性可能会在将来导致各种问题。

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

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

obj.setX(10);

in Java, becomes

在Java中,成为

obj.X = 10;

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

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

#5


2  

I personally like the following rule:

我个人喜欢以下规则:

  • Use the get prefix whenever the value is directly modifiable with a corresponding set method
  • 只要值可以使用相应的set方法直接修改,就可以使用get前缀

  • 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)
  • 在值不能直接设置为属性的情况下删除get前缀(即没有等效的setXXX方法)

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.

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

Examples:

  • String.length() - since strings are immutable, length is a read-only value
  • String.length() - 因为字符串是不可变的,所以length是只读值

  • ArrayList.size() - size changes when elements are added or removed, but you can't set it directly
  • ArrayList.size() - 添加或删除元素时大小会更改,但您无法直接设置它

#6


1  

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.

它当然是API经常暴露只读属性而没有get前缀的情况:String.length()甚至更新的Buffer.capacity()是合理的例子。

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 :)

当然,在C#中,它几乎无关紧要,因为无论如何都有“真正的”属性:)

#7


1  

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

在C ++中,代替getAttr()/ setAttr()对,通常提供两个Attr()函数的重载:void Attr(Foo f); // setter Foo Attr(); //吸气剂

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.

在Java中,通常的做法是为get / set添加前缀。我不得不说最好的做法是遵循你的语言标准。在Java中,人们希望看到获取/设置前缀,因此省略它们可能会使人感到困惑,即使它们并非严格必要。

#8


0  

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

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

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).

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

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.

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

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.

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

#9


0  

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; }

只是一个简短的附录:另一个惯例是布尔字段的getter以“is”而不是“get”为前缀,例如bool isEnabled(){return enabled; }

#1


5  

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.

它归结为语义。是的,C#有“属性”,它为你提供了一个get / set'方法'存根......但.NET Framework中以“Get”开头的函数(...“methods”...)应该提示开发人员认为某些操作正在发生,其唯一目的是获得一些结果。

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.

只需使用该方法的名称,您就可以假设正在对数据库中的人进行100%“安全”检索。

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).

你永远不会多次打电话给“CreatePerson”......但是你应该总是安全地打电话给“GetPerson”。 (它不应该影响应用程序的“状态”)。

#2


4  

"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.

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

#3


4  

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

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

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...

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

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.

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

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

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

#4


2  

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.

Java(尚未)支持属性。吸气剂和二传手是一个可以解决这个问题的小屋。其他语言 - 包括C# - 支持属性,您应该使用它们。这不仅仅是“最佳实践”的事情:C#中的序列化将依赖于属性,而不是依赖于getter和setter,因此如果您需要序列化类,不使用属性可能会在将来导致各种问题。

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

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

obj.setX(10);

in Java, becomes

在Java中,成为

obj.X = 10;

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

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

#5


2  

I personally like the following rule:

我个人喜欢以下规则:

  • Use the get prefix whenever the value is directly modifiable with a corresponding set method
  • 只要值可以使用相应的set方法直接修改,就可以使用get前缀

  • 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)
  • 在值不能直接设置为属性的情况下删除get前缀(即没有等效的setXXX方法)

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.

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

Examples:

  • String.length() - since strings are immutable, length is a read-only value
  • String.length() - 因为字符串是不可变的,所以length是只读值

  • ArrayList.size() - size changes when elements are added or removed, but you can't set it directly
  • ArrayList.size() - 添加或删除元素时大小会更改,但您无法直接设置它

#6


1  

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.

它当然是API经常暴露只读属性而没有get前缀的情况:String.length()甚至更新的Buffer.capacity()是合理的例子。

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 :)

当然,在C#中,它几乎无关紧要,因为无论如何都有“真正的”属性:)

#7


1  

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

在C ++中,代替getAttr()/ setAttr()对,通常提供两个Attr()函数的重载:void Attr(Foo f); // setter Foo Attr(); //吸气剂

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.

在Java中,通常的做法是为get / set添加前缀。我不得不说最好的做法是遵循你的语言标准。在Java中,人们希望看到获取/设置前缀,因此省略它们可能会使人感到困惑,即使它们并非严格必要。

#8


0  

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

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

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).

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

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.

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

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.

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

#9


0  

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; }

只是一个简短的附录:另一个惯例是布尔字段的getter以“is”而不是“get”为前缀,例如bool isEnabled(){return enabled; }