سؤال

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.

Yes It's good practice to use a meaningful parameter name rather than short and not understandable name.

It would be better if you are using the same name as the instance field name to make it more clear.

By using this you can benefit of Auto JavaDoc that uses the parameters names.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top