Skip to Content
Author's profile photo Richard Birenheide

Closures in Java announced for Dolphin: Preservation of the local environment

The consequences of accessing the local scope become clear, if one tries to define more than one closure in sequence. Since closures are allowed to manipulate variables in local scope, these closures become coupled. There are very prominent circumstances where nowadays Java closures, namely anonymous inner classes are not executed synchronously, the most prominent ones probably being listeners and runnables. The latter are rarely found to be defined in the same scope, but for the former I’ve seen dozens of examples and I do that myself from time to time. What does that mean for local variables? They get the same scope as a freely accessible instance variable, i.e. they can be manipulated from different parts of the coding at different times. Especially when debugging it might not be obvious that the value of the variable is changed from elsewhere. As in my Closures in Java announced for Dolphin: non-local returns I simulate that situation with a code snippet in current Java:

One easily could think about a similar example for registering listeners. I personally would judge the coding above as bad practice and discourage using such a pattern. In my opinion, introducing closures would possibly encourage this kind of pattern and make maintenance and bugtracking much more difficult.

Assigned Tags

      Be the first to leave a comment
      You must be Logged on to comment or reply to a post.