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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With