When to use field variable?
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.
开发者_StackOverflow中文版Thanks,
Sarah
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.
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.
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.
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.
精彩评论