Do Not Re-Assign Parameters

Summary

Parameters to methods should never be re-assigned.

Detail

Reassigning to parameters makes code harder to understand and provides no meaningful advantage over creating a new variable.

If the method is large, it can be difficult to track the lifecycle of a parameter. Even within short methods, re-using parameters will cause problem. As the variable is being used to represent two separate concepts, it is often not possible to name it meaningfully.

If another variable of the same type as a parameter is needed, it should be declared locally.

Bad

  1. public String foo(String currentStatus) {
  2. if ( someLogic() ) {
  3. currentStatus = "FOO";
  4. }
  5. return currentStatus;
  6. }

Better

  1. public String foo(final String currentStatus) {
  2. String desiredStatus = currentStatus;
  3. if ( someLogic() ) {
  4. desiredStatus = "FOO";
  5. }
  6. return desiredStatus ;
  7. }

Parameters may be declared final so that the reader can tell at a glance that its value will not change.