Best practice for parameter naming in Java constructors and simple setters

Uri picture Uri · Jun 14, 2009 · Viewed 26k times · Source

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

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

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

I have commonly seen the following three options:

1) Use the actual field name with an underscore:

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

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

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) Completely inconsistent things like:

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.

Answer

Nat picture Nat · Jun 14, 2009

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.