Java – Better Style: Instance Variable vs. Return Value in Java

coding-stylejava

I often find myself struggling to decide which of these two ways to use when I require to use common data across some methods in my classes. What would be a better choice?

In this option, I can create an instance variable to avoid the need of having to declare additional variables, and also to avoid defining method parameters, but it may be not so clear where those variables are being instantiated/modified:

public class MyClass {
    private int var1;

    MyClass(){
        doSomething();
        doSomethingElse();
        doMoreStuff();
    }

    private void doSomething(){
        var1 = 2;
    }

    private void doSomethingElse(){
        int var2 = var1 + 1;
    }

    private void doMoreStuff(){
        int var3 = var1 - 1;
    }
}

Or just instantiating local variables and passing them as arguments?

public class MyClass {  
    MyClass(){
        int var1 = doSomething();
        doSomethingElse(var1);
        doMoreStuff(var1);
    }

    private int doSomething(){
        int var = 2;
        return var;
    }

    private void doSomethingElse(int var){
        int var2 = var + 1;
    }

    private void doMoreStuff(int var){
        int var3 = var - 1;
    }
}

If the answer is that they are both correct, which one is seen/used more often? Also, if you can provide additional pros/cons for each option would be very valuable.

Best Answer

I'm surprised this hasn't mentioned yet...

It depends if var1 is actually part of your object's state.

You assume that both of these approaches are correct and that it's just a matter of style. You are wrong.

This is entirely about how to properly model.

Similarly, private instance methods exist to mutate your object's state. If that's not what your method is doing then it should be private static.