1

There is a variable that must persist between calls but otherwise only one method uses it.

As it is a method of the object, the value can be persisted as a private field of the object, or otherwise it can be persisted as a static variable within the method. The initial value is trivial and can be easily assigned in any case.

Is there any consensus view which approach should be more appropriate?

1 Answer 1

6

They mean different things: static variable within the method is the same across all objects, whereas private field can have different values for different objects.

You can also have a private static field which has the same values across all objects.

Generally static variable within methods are discouraged as they are hard to "see", while object fields are grouped together.

The initial value is trivial and can be easily assigned in any case.

This can be quite complicated in multithreaded situations, to ensure it's initialised "exactly once".

1
  • There is only one instance of this object, anyway I will make it a field following this recommendation.
    – h22
    Commented Sep 19, 2023 at 12:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.