Search code examples
javamethodsmutators

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


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?


Solution

  • 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.