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);
}
That effectively does this:
E.g., first sets the instance member
lastNameto the argumentlastNameand 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
lastNameonly needs to happen once, and then that value is assigned tothis.lastNameand 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:
More rare when calling a function, but quite common in that kind of loop.
You also see it in compound assignment, e.g.:
…which calls
foo(), setszto the return value, then setsyto that same value, then setsxto that same value (without, obviously, repeating the call).