Search code examples
javaclass-variables

To class variable or not to class variable?


I got a class Foo having a method doSomething that uses two class-related variables b and c that are expensive to get/create. My first version looks like this:

public class Foo {

    private final A a;

    public Foo(A a) {
        this.a = a;
    }

    public void doSomething() {
        final B b = a.getB();
        final C c = b.getC();

        for (int i = 0; i < 1000; i++) {
            // do something with b and c
        }
    }
}

So I get the first object (type B) via a class variable a and the second object (type C) via the first object.

Now, since those variables are related to the class and the method is always called exactly one time (though not necessarily when creating an object of type Foo), I thought about making them class variables as well:

public class Foo {

    private final A a;
    private final B b;
    private final C c;

    public Foo(A a) {
        this.a = a;
        b = a.getB();
        c = b.getC();
    }

    public void doSomething() {
        for (int i = 0; i < 1000; i++) {
            // do something with b and c
        }
    }
}

I'm not sure which version to use if any of those two. I somehow don't feel comfortable making those two variables class members since they can be retrieved from the existing class variable a. However, it would increase readability of the methods IMO.


Solution

  • You are absolutely right. If it increases readability, bu all means do it. However, I would ask you this: What is the purpose of Referencing A from within the class? Is it only for getting B and C? In this case, I would just input B and C in Foo's constructor!

    This way you even make it more readable by breaking the dependency on A and Making the dependency on B and C more explicit.

    Also, consider whether you are using these variables in other methods in the class. If the answer is yes- it signals that they should be class members, However, if the class contains a lot of methods that do not use these variables, that might signal the opposite.

    The general principle you should follow here is the principle of High Cohesion