Java构造函数和简单setter中参数命名的最佳实践 [英] Best practice for parameter naming in Java constructors and simple setters

查看:152
本文介绍了Java构造函数和简单setter中参数命名的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我已经看到了C ++的答案,但两个社区的实践经常不同。)

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

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

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

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

I have commonly seen the following three options:

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

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



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



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

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



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



3) Completely inconsistent things like:

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

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

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

推荐答案

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

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构造函数和简单setter中参数命名的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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