Java Instance Variables vs Local Variables

2019-01-07 10:23发布

I'm in my first programming class in high school. We're doing our end of the first semester project. This project only involves one class, but many methods. My question is best practice with instance variables and local variables. It seems that it would be much easier for me to code using almost only instance variables. But I'm not sure if this is how I should be doing it or if I should be using local variables more (I would just have to have methods take in the values of local variables a lot more).

My reasoning for this is also because a lot of times I'll want to have a method return two or three values, but this is of course not possible. Thus it just seems easier to simply use instance variables and never having to worry since they are universal in the class.

10条回答
时光不老,我们不散
2楼-- · 2019-01-07 10:25

Use instance variable when

  1. If 2 functions in the class need the same value then make it instance variable OR
  2. If the state is not expected to change make it instance variable. eg: immutable object, DTO, LinkedList, those with final variables OR
  3. If it is an underlying data on whom actions are performed. eg: final in arr[] in PriorityQueue.java source code OR
  4. Even if it is used only once && state is expected to change, make it instance if it is used only once by a function whose parameter list should be empty. eg: HTTPCookie.java Line: 860 hashcode() function uses 'path variable'.

Similarly Use local variable when none of these conditions match, specifically role of the variable would end after stack is popped off. eg: Comparator.compare(o1, o2);

查看更多
走好不送
3楼-- · 2019-01-07 10:29

Generally variables should have minimal scope.

Unfortunately, in order to build classes with minimized variable scope, one often needs to do a lot of method parameter passing.

But if you follow that advice all the time, perfectly minimizing variable scope, you may end up with a lot of redundancy and method inflexibility with all the required objects passed in and out of methods.

Picture a code base with thousands of methods like this:

private ClassThatHoldsReturnInfo foo(OneReallyBigClassThatHoldsCertainThings big,
 AnotherClassThatDoesLittle little) {
    LocalClassObjectJustUsedHere here;
             ...
}
private ClassThatHoldsReturnInfo bar(OneMediumSizedClassThatHoldsCertainThings medium,
 AnotherClassThatDoesLittle little) {
    ...
}

And, on the other hand, imagine a code base with lots of instance variables like this:

private OneReallyBigClassThatHoldsCertainThings big;
private OneMediumSizedClassThatHoldsCertainThings medium;
private AnotherClassThatDoesLittle little;
private ClassThatHoldsReturnInfo ret;

private void foo() { 
    LocalClassObjectJustUsedHere here; 
    .... 
}
private void bar() { 
    .... 
}

As code increases, the first way may minimize variable scope best, but can easily lead to a lot of method parameters being passed around. The code will usually be more verbose and this can lead to a complexity as one refactors all these methods.

Using more instance variables can reduce the complexity of lots of method parameters being passed around and can give a flexibility to methods when you are frequently reorganizing methods for clarity. But it creates more object state that you have to maintain. Generally the advice is to do the former and refrain from the latter.

However, very often, and it may depend on the person, one can more easily manage state complexity compared with the thousands of extra object references of the first case. One may notice this when business logic within methods increases and organization needs to change to keep order and clarity.

Not only that. When you reorganize your methods to keep clarity and make lots of method parameter changes in the process, you end up with lots of version control diffs which is not so good for stable production quality code. There is a balance. One way causes one kind of complexity. The other way causes another kind of complexity.

Use the way that works best for you. You will find that balance over time.

I think this young programmer has some insightful first impressions for low maintenance code.

查看更多
何必那么认真
4楼-- · 2019-01-07 10:30

Try to think about your problem in terms of objects. Each class represents a different type of object. Instance variables are the pieces of data that a class needs to remember in order to work, either with itself or with other objects. Local variables should just be used intermediate calculations, data that you don't need to save once you leave the method.

查看更多
forever°为你锁心
5楼-- · 2019-01-07 10:31

Short story: if and only if a variable needs to be accessed by more than one method(or outside of the class) create it as an instance variables. If you need it only locally, in a single method, it has to be a local variable. Instance variables are more costly than local variables.
Keep in mind: instance variables are initialized to default values while local variables are not.

查看更多
劫难
6楼-- · 2019-01-07 10:34

Local variables internal to methods are always prefered, since you want to keep each variable's scope as small as possible. But if more than one method needs to access a variable, then it's going to have to be an instance variable.

Local variables are more like intermediate values used to reach a result or compute something on the fly. Instance variables are more like attributes of a class, like your age or name.

查看更多
做自己的国王
7楼-- · 2019-01-07 10:34

The easy way: if the variable must be shared by more than one method, use instance variable, otherwise use local variable.

However, the good practice is to use as more local variables as possible. Why? For your simple project with only one class, there is no difference. For a project that includes a lot of classes, there is big difference. The instance variable indicates the state of your class. The more instance variables in your class, the more states this class can have and then, the more complex this class is, the hard the class is maintained or the more error prone your project might be. So the good practice is to use as more local variable as possible to keep the state of the class as simple as possible.

查看更多
登录 后发表回答