Search code examples
javaobserver-pattern

Setting instance field value inside method argument


I encountered the following code while looking up an example of the Observer pattern. The 4th argument is a String, but I was wondering what happens there: Does it set the instance field lastName to the new lastName value and then return this lastName?

Is this form of shortening common practice?

 public void setLastName(String lastName) {
  notifyListeners(this, "lastName", lastName, this.lastName = lastName);
}

Solution

  • That effectively does this:

    public void setLastName(String lastName) {
      this.lastName = lastName;
      notifyListeners(this, "lastName", lastName, lastName);
    }
    

    E.g., first sets the instance member lastName to the argument lastName and then uses that same value again when calling the function.

    I wouldn't say it's that common, though there are some idioms that use it (see below); in that specific case, there's no particularly good reason for doing it. The idea is that the "get from variable" operation reading lastName only needs to happen once, and then that value is assigned to this.lastName and also passed to the function. But the compiler and JVM are more than up to making sure clear code (within reason) is efficient, whereas they can't help people understand confusing code. :-)

    As jlordo points out in the comments, there are some idioms where this kind of assign-and-use is common, for instance:

    while ((line = in.readLine()) != null) {
        // ...
    }
    

    More rare when calling a function, but quite common in that kind of loop.

    You also see it in compound assignment, e.g.:

    x = y = z = foo();
    

    ...which calls foo(), sets z to the return value, then sets y to that same value, then sets x to that same value (without, obviously, repeating the call).