2

In Netty I have seen object member variables assigned locally in class methods quite frequently. Is this a matter of style or is there a programmatic benefit?

I have included a code snippet below:

public ChannelFuture bind() {
    validate();
    SocketAddress localAddress = this.localAddress;
    if (localAddress == null) {
        throw new IllegalStateException("localAddress not set");
    }
    return doBind(localAddress);
}
MWright
  • 1,521
  • 2
  • 16
  • 31
  • 2
    Notice that `bind()` returns a `ChannelFuture`? I believe that is kept so that a change to the *instance's* `localAddress` doesn't effect the result of the bind call (which might not complete until sometime in the future). – Elliott Frisch Mar 29 '16 at 20:12

1 Answers1

2

I usually see that pattern when multi-threading is a concern. For example, if another thread may alter the member value or null it after the null check, yet it is still a valid use case for member access to occur at that point. Or the code is trying to avoid locks/synchronization. So instead the member is copied to a local and all further operations are done using the local copy to prevent a null access.