0

Under what circumstance would you use field variable instead of local variable? I found it a bit hard to decide when a variable is used in 2 or more methods in a class. I tend to use local variables and pass them to another method.

Thanks,

Sarah

sarahTheButterFly
  • 1,894
  • 3
  • 22
  • 36
  • Related/duplicate: http://stackoverflow.com/questions/1794141/java-instance-variables-vs-local-variables – Steve Kuo Aug 19 '10 at 23:57

4 Answers4

8

In object-oriented terms, does the variable make sense as an attribute of the object? If so, you should make it a field variable. If not, it can go either way.

Remember the Single Responsibility Principle -- well-designed classes should have only 1 responsibility, and thus only 1 reason to change.

Kaleb Brasee
  • 51,193
  • 8
  • 108
  • 113
7

A field denotes some kind of state related to an instance of your class. For instance, a BankAccount could have a balance field.

You should never use a field to simplify passing data from one method to another method. That's simply not its purpose. Doing so also makes your methods intrinsically thread unsafe or require synchronization.

A local variable is just a temporary store of data used to support an operation being done by a method. For example,

public void addInterest(double rate) {
    double toAdd = rate * balance;
    logTransaction("Interest", toAdd);
    balance += toAdd;
}

toAdd here makes no sense as a field since it is temporary to the operation, not a part of the account's state.

Mark Peters
  • 80,126
  • 17
  • 159
  • 190
1

I would definitely not pass variables around to other methods unless there's a very specific reason. If the variable is used multiple times in the class, make it a field variable. This almost always makes your code much more flexible too.

In general, you can also think if the variable makes sense as a part of the class. That is, it makes sense to have a Car class have the variable numOfMiles, even if it's only used a few times. However, if one method is int GetAmountOfGasUsed(int milesThisTrip) it makes sense to pass in the miles variable as a local variable because the distance you travel is probably not specific to the car.

Nate
  • 2,462
  • 1
  • 20
  • 28
0

If the methods that use the variable need to modify the value as well, then by all means make it a field variable. But, if they only read the value, you can safely pass it around.

Alfero Chingono
  • 2,663
  • 3
  • 33
  • 54