Limit Variables to the Smallest Possible Scope

Summary

Variables should be declared as late as possible so that they have the narrowest possible scope.

Details

Bad

  1. public void foo(String value) {
  2. String calculatedValue;
  3. if (someCondition()) {
  4. calculatedValue = calculateStr(value);
  5. doSomethingWithValue(calculatedValue);
  6. }
  7. }

Better

  1. public void foo(String value) {
  2. if (someCondition()) {
  3. String calculatedValue = calculateStr(value);
  4. doSomethingWithValue(calculatedValue);
  5. }
  6. }

Better still

  1. public void foo(String value) {
  2. if (someCondition()) {
  3. doSomethingWithValue(calculateStr(value));
  4. }
  5. }

Sometimes, assigning to well-named, temporary variables will result in more readable code than calling a method inline because it helps the reader follow the data and logical flow.

As a rule of thumb, if you are unable to come up with a name for a variable that does little more than mirror a method from which its value was retrieved, then the variable should be eliminated.