Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class field naming vs method parameter naming

Tags:

java

standards

What is considered best practice when it comes to naming class fields vs. method parameters in the same class?

For example, if I have a field named transactionType, should I also name the parameter in my setter method transactionType and just refer to the field using this.transactionType?

I am not asking for an opinion, I just want to know if this is acceptable or would it be considered confusing since there are two uses of the same name (though obviously different in scopes).

like image 770
trevorkavanaugh Avatar asked Jan 10 '23 14:01

trevorkavanaugh


2 Answers

It is standard Java idiom to use the same name for the parameter as for the field, in both setter methods and constructors. Your IDE will probably propose such parameter names when you ask it to create a setter or parameterized constructor.

Within such methods, you must use this. to specify the field; the unadorned name refers to the parameter. transactionType means the parameter while this.transactionType means the field.

like image 124
Carl Manaster Avatar answered Jan 13 '23 02:01

Carl Manaster


Yes, using the same identifier and this. is acceptable and commonly done. I've done it with others in large projects and it works fine, at least when the project uses static analysis tools (such as IntelliJ inspections) to catch the occasional conflict.

There is no standard; no-one is in charge of Java code style. Use what works well for you. Even popular code standards usually have a dumb thing or two in them. You be the judge.

like image 44
Dave Schweisguth Avatar answered Jan 13 '23 02:01

Dave Schweisguth