Java 构造函数和简单 setter 中参数命名的最佳实践

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/991757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:57:05  来源:igfitidea点击:

Best practice for parameter naming in Java constructors and simple setters

javanaming

提问by Uri

Is there a standard acceptable convention for parameters in Javato straightforward constructors and setters?

Java 中的参数对于简单的构造函数和 setter是否有标准的可接受约定?

(I've seen the answer for C++, but practices are often different between the two communities)

我已经看到了 C++ 的答案,但是两个社区之间的做法往往不同)

Suppose that I have a class C with a foo field.

假设我有一个带有 foo 字段的 C 类。

I have commonly seen the following three options:

我经常看到以下三个选项:

1) Use the actual field name with an underscore:

1) 使用带下划线的实际字段名称:

public C(Type foo_)
{
   foo = foo_;
}

public void setFoo(Type foo_)
{
   foo = foo_;
}

2) Use the actual field name, just use "this" in setting:

2)使用实际的字段名称,只需在设置中使用“this”:

public C(Type foo)
{
   this.foo = foo;
}
public void setFoo(Type foo)
{
   this.foo = foo;
}

3) Completely inconsistent things like:

3)完全不一致的事情,例如:

public C(Type bar)
{
   this.foo = bar;
}
public void setFoo(Type bar)
{
   this.foo = bar;
}

I tend to use 2, but I'm wondering what's correct practice.

我倾向于使用 2,但我想知道什么是正确的做法。

采纳答案by Nat

Option two is most common. In Java it's considered poor practice to use meaningless name prefixes or suffixes to distinguish instance variables from parameters from local variables. But there are no conventions for the names themselves. Use whatever names make the code easiest to understand.

选项二是最常见的。在 Java 中,使用无意义的名称前缀或后缀来区分实例变量和参数以及局部变量被认为是不好的做法。但是名称本身没有约定。使用使代码最容易理解的任何名称。

回答by neesh

I have seen 2 and 3 used the most. That said, the answer is dictated by what the accepted standard is for the code base you are contributing to. I think it is more important to be consistent across the project than have one "right" answer for every single java developer.

我见过2和3用得最多。也就是说,答案取决于您所贡献的代码库的公认标准。我认为在整个项目中保持一致比为每个 Java 开发人员提供一个“正确”的答案更重要。

Eclipse code genration uses style #2 from your list.

Eclipse 代码生成使用列表中的样式 #2。

回答by soldier.moth

I know that when netbeans automatically creates getters and setters it uses number 2 method. I personally usually add temp to the variable i.e foo = tempfoo. But as neesh says you should try to remain consistent regardless of which method you choose

我知道当 netbeans 自动创建 getter 和 setter 时,它使用 2 号方法。我个人通常将 temp 添加到变量 ie 中foo = tempfoo。但是正如neesh所说,无论选择哪种方法,您都应该尝试保持一致

回答by cletus

(1) is very C/C++. Java doesn't tend to use leading underscores much.

(1) 非常C/C++。Java 不太倾向于使用前导下划线。

I personally use (2) almost exclusively.

我个人几乎只使用(2)。

(3) is just making your life difficult because it can be hard to think of two meaningful yet concise names for the member and the parameter.

(3) 只是让您的生活变得困难,因为很难为成员和参数想到两个有意义但简洁的名称。

回答by Humphrey Bogart

As you code to make the interface as clear as possible, I always prefer using a field as _nameinternally, having it as nameas a method argument, assigning it elegantly as _name = name. I have seen this in Fowler's Refactoring and other similar textbooks, though I see ugly mechanisms such as using the field as nameinternally then using aNameas a method argument, ugh.

当您编写代码以使界面尽可能清晰时,我总是更喜欢在_name内部使用字段,将其作为name方法参数,优雅地将其分配为_name = name. 我在 Fowler 的 Refactoring 和其他类似的教科书中看到了这一点,尽管我看到了丑陋的机制,例如在name内部使用该字段然后aName作为方法参数使用,呃。

回答by coobird

I've also seen the Option 2 as the most common one:

我也将选项 2 视为最常见的选项:

int importance;

public int getImportance()
{
    return importance;
}

public void setFoo(int importance)
{
    this.importance = importance;
}

IDEs such as Eclipse and Netbeans will automatically write the getters and setters in the above format.

Eclipse 和 Netbeans 等 IDE 会自动以上述格式编写 getter 和 setter。

There are a few merits to using this method:

使用这种方法有几个优点:

Does not use the underscore (_) character in the field name -- underscores are not recommended for non-constant field names.

不在_字段名称中使用下划线 ( ) 字符 - 不建议对非常量字段名称使用下划线。

The use of the underscore character in an identifier is not recommended except for identifiers for constants.

不建议在标识符中使用下划线字符,常量标识符除外。

The Variablespage of The Java Tutorials mentions the following about underscores:

The Java Tutorials的Variables页面提到了以下关于下划线的内容:

If your variable stores a constant value, such as static final intNUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

如果您的变量存储一个常量值,例如static final intNUM_GEARS = 6,约定略有变化,将每个字母大写并用下划线字符分隔后续单词。按照惯例,下划线字符永远不会在其他地方使用。

(Emphasis added.)

(加了重点。)

Since field names are not constants, according to what is written on that page, one should not use underscores in non-constant fields.

由于字段名称不是常量,根据该页面上写的内容,不应在非常量字段中使用下划线。

IDEs can automatically add Javadoc comments according to the name of the parameter of the method, so having the name of the field in the parameter list would be beneficial.

IDE 可以根据方法的参数名称自动添加 Javadoc 注释,因此在参数列表中包含字段名称将是有益的。

The following is an example of an automatically generated Javadoc:

以下是自动生成的 Javadoc 的示例:

/**
 *
 * @param importance  <-- Parameter name in Javadoc matches
 *                        the parameter name in the code.
 */
public void setImportance(int importance)
{
    this.importance = importance;
}

Having the Javadoc reflect the name of the field has another benefit -- IDEs that have code completion can use the field name in the Javadoc in order to automatically fill out parameter names:

让 Javadoc 反映字段名称还有另一个好处——具有代码完成功能的 IDE 可以使用 Javadoc 中的字段名称来自动填写参数名称:

// Code completion gives the following:
this.getImportance(importance);

Giving meaning to the field name and parameter name will make it easier to understand what the parameter actually represents.

为字段名称和参数名称赋予含义将更容易理解参数实际代表什么。

Those are some of the merits I can come up with at the moment, and I believe that it is most likely the most common way to naming parameters in Java.

以上是我目前能想到的一些优点,我相信这很可能是 Java 中最常用的参数命名方式。

回答by Thorbj?rn Ravn Andersen

Option two.

选项二。

If you see a "setFoo(String foo)" definition (e.g. in javadoc or hover) you would be reasonable to expect that the field "foo" is set to the value of the parameter "foo". Other names may require you to double check - e.g. would setName(String person) just set the name to person or would additional action be taken (look up the name in a table of persons etc)?.

如果您看到“setFoo(String foo)”定义(例如在javadoc 或hover 中),您可以合理地期望字段“foo”被设置为参数“foo”的值。其他名称可能需要您仔细检查 - 例如将 setName(String person) 只是将名称设置为 person 还是会采取其他操作(在人员表中查找名称等)?。

The usual reason for not doing so is that you may accidentially write

不这样做的通常原因是你可能会不小心写

... foo = foo;

... foo = foo;

instead of

代替

this.foo = foo;

this.foo = foo;

which is a self-assignment of the parameter not doing anything. Modern compilers catch this - modern IDE generates the "this.foo = foo" statement when creating a setter for a field.

这是参数的自我分配,不做任何事情。现代编译器抓住了这一点 - 现代 IDE 在为字段创建 setter 时生成“this.foo = foo”语句。

In Eclipse you can create the getter and setter for a field, with Ctrl-1 when the cursor is located on the field in question.

在 Eclipse 中,您可以为字段创建 getter 和 setter,当光标位于相关字段上时,使用 Ctrl-1。

回答by Jill Renee

the convention that I use is to preface member variables with m_; as in:

我使用的约定是在成员变量前加上 m_; 如:

String m_foo;

字符串 m_foo;

that way, it is very clear which variables are members and which are not.

这样,很清楚哪些变量是成员,哪些不是。

also, my last company prefaced all the arguments in a method with "the", as in:

此外,我的最后一家公司在一个方法中的所有参数都以“the”开头,如下所示:

public doFoo(String theKey, String theRandom) {

公共 doFoo(String theKey, String theRandom) {

....

....

}

}

it made it very easy to not confuse the arguments with internal variables.

这使得不将参数与内部变量混淆非常容易。

conventions should be about making the code easier to read, and reducing errors.

约定应该是使代码更易于阅读,并减少错误。

回答by Guest

Option 2 is most common in Java but a picky Checkstyle won't let you use this option because the name of the local var shadows the other.

选项 2 在 Java 中最常见,但挑剔的 Checkstyle 不会让您使用此选项,因为本地变量的名称会影响另一个变量。

Because of that most use the following:

因此,大多数使用以下内容:

foo(int thatBar) { this.bar = thatBar; }

foo(int thatBar) { this.bar = thatBar; }

The only problem using this option is that others may guess that you are using a var named bar in your class because if not you wouldn't name the parameter so.

使用此选项的唯一问题是其他人可能会猜测您在类中使用了名为 bar 的 var,因为否则您不会这样命名参数。

An evil person could use that information to better understand your class only by looking at the methods. But for that you would use an obfuscator which renames all vars etc.

邪恶的人只能通过查看方法来使用这些信息来更好地了解您的课程。但是为此,您将使用一个混淆器来重命名所有变量等。

回答by GhostCat

Yes option 2 is most widely used; although it has a severe problem: if you have a typo in the declaration of your parameter - that might go unnoticed because of shadowing, like:

是的,选项 2 使用最广泛;虽然它有一个严重的问题:如果你的参数声明中有一个错字 - 由于shadowing,这可能会被忽视,例如:

class Whatever { 
  String val;
  Whatever(String va1) { this.val = val; }
  void printMe() { System.out.println(val.toString()); }
  public static void main(String[] args) {
    new Whatever("Hello").printMe();
  }
}

This code compiles fine; and it takes you a second to understand what is wrong in there. If you are in doubt; just print it out; take it to your coworkers and ask them what will happen if this class is compiled and executed. My guess: 75%+ will notrealize that a NullPointerException will be thrown. And if you turn to a font that "looks the same" for val and va1; then nobody will notice from reading ...

这段代码编译得很好;你需要一秒钟才能理解那里有什么问题。如果您有疑问;只需打印出来;把它拿给你的同事,问他们如果编译和执行这个类会发生什么。我的猜测:75%+不会意识到将抛出 NullPointerException。如果你转向 val 和 va1 的“看起来相同”的字体;那么没有人会从阅读中注意到......

Yes, nowadays you might see a warning about that, or some code checking tool tells you that this happened; and of course, your unit tests should find it immediately.

是的,现在你可能会看到一个警告,或者一些代码检查工具告诉你发生了这种情况;当然,您的单元测试应该立即找到它。

But: if you avoid this pattern, and use prefixes or "thatString" you will never hit this problem in the first place. Thus I really don't understand why it is so commonly used.

但是:如果您避免这种模式,并使用前缀或“thatString”,您将永远不会遇到这个问题。因此我真的不明白为什么它如此常用。

So, we sat down in our team and when putting together our coding style guide we said: never use option 2.

所以,我们在我们的团队中坐下来,在整理我们的编码风格指南时,我们说:永远不要使用选项 2。