sarahTheButterFly
sarahTheButterFly

Reputation: 1952

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.

Thanks,

Sarah

Upvotes: 1

Views: 2644

Answers (4)

Mark Peters
Mark Peters

Reputation: 81074

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.

Upvotes: 7

Nate
Nate

Reputation: 2492

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.

Upvotes: 1

Kaleb Brasee
Kaleb Brasee

Reputation: 51935

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.

Upvotes: 8

Alfero Chingono
Alfero Chingono

Reputation: 2663

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.

Upvotes: 0

Related Questions