How does one know if a certain method will change the state of a java object?

Viewed 484

Some methods are mutator methods, usually they return nothing, the so-called setters. Others, like the .plusDays() method of the LocalDate class, return a full, instantiated object of type Localdate, so if you want to change the object, you need to point your existing object variable to the newly created one.

Is there a way to know beforehand if a method will be a mutator, or work like the before-mentioned apart from looking at its return value?

2 Answers

No, there is no way to know (short of looking at the documentation or implementation) whether a method will change some sort of state.

Methods that return void are generally going to change some sort of state (otherwise what are they doing?), but there's still no guarantee what will change (options include the object, one of its fields, the method's parameters, global state, or even the JVM runtime itself).

There's no general-purpose way to tell whether methods that return something will also have other side-effects or not.

If a type is immutable you can be confident that none of its methods will mutate its own state, but then the question has simply shifted to "how do you tell whether a type is immutable or not?" This is easier to answer, but still tricky. Static analysis tools like ErrorProne's @Immutable check are helpful but still fallible.

Well, pure setters which follow the pattern void setProperty(PropertyType property) are likely to modify the internal state (ok, one could implement it in a different way, e.g. modify the state of the passed parameter, but that would be strange).

Methods found in Builders for instance (like Builder withProperty(PropertyType property)) are free to choose whether they update the state of the actual instance or create and return new instance holding the updated property.

In the end one cannot foresee whether one or the other implementation strategy has been chosen just by looking at the method, so one has to read the docs (and sometimes the code).

Related