warpedjavaguy

Imperative by day and functional by night

Posts Tagged ‘closures

Polymorphism by Closure Injection?


Instead of defining many classes to do the same thing differently through polymorphism, you could define just one class and achieve the same through closure injection!
 

I recently downloaded the feature complete BGGA closures prototype and had a bit of a play. My first experiment was to refactor an existing codebase and replace all anonymous inner classes with closures. The ones that extended single abstract method (SAM) interfaces were easy to convert. The ones that extended multiple method (non-SAM) types were a bit trickier. In the end though, I managed to successfully convert all of them, and with very little effort.

In converting the non-SAM types, I discovered that the functional equivalent of polymorphism can be achieved by injecting closures into a single concrete implementation having no subclasses.

The codebase I refactored was a small (fictitious) railroad application that provided customers with information about routes. In particular, it calculated things like the number of routes between two cities, the number of routes that do not exceed a given number of stops, the distances of individual routes, and the like. It did this by deriving routes on the fly from a given set of legs and dynamically yielding only those that match a given predicate (or condition).

Here is the original predicate code using anonymous inner classes:

public abstract class Predicate<T> {

  public boolean eligible(T item) {
    return yield(item);
  }

  public abstract boolean yield(T item);

  /* Pre-defined predicates follow */

  public static Predicate<Route> routesWithMaxStops(final int maxStops) {
    return new Predicate<Route>() {
      public boolean yield(Route route) {
        return route.getLegs().size() <= maxStops;
      }
    };
  }

  public static Predicate<Route> routesWithStops(final int stops) {
    return new Predicate<Route>() {
      public boolean eligible(Route route) {
        return route.getLegs().size() <= stops;
      }
      public boolean yield(Route route) {
        return route.getLegs().size() == stops;
      }
    };
  }

}

In the above code only two predefined predicates are shown for brevity (the actual code has got more).

Note that the predicate has two methods. Only routes for which both methods return true are yielded.

  • eligible – determines if a route satisfies a boundary condition
  • yield – determines if a route should be yielded

Here is the converted closure equivalent:

public class Predicate<T> {

  private {T => boolean} eligible;
  private {T => boolean} yield;

  public Predicate({T => boolean} yield) {
    this(yield, yield);
  }

  public Predicate({T => boolean} eligible, {T => boolean} yield) {
    this.eligible = eligible;
    this.yield = yield;
  }

  public boolean eligible(T item) {
    return eligible.invoke(item);
  }

  public boolean yield(T item) {
    return yield.invoke(item);
  }

  /* Pre-defined predicates follow */

  public static Predicate<Route> routesWithMaxStops(int maxStops) {
    return new Predicate<Route>(
      {Route route => route.getLegs().size() <= maxStops});
  }

  public static Predicate<Route> routesWithStops(int stops) {
    return new Predicate<Route>(
      {Route route => route.getLegs().size() <= stops},
      {Route route => route.getLegs().size() == stops});
  }

}

If you look carefully, you will notice that both the original and converted code produce a redundant invocation when the eligible and yield expressions are identical. Fortunately, this is a flaw that can be very easily corrected in the closure version.

A possible correction is shown below (see lines 5, 17, 18, and 22):

public class Predicate<T> {

  private {T => boolean} eligible;
  private {T => boolean} yield;
  private boolean isEligible;

  public Predicate({T => boolean} yield) {
    this(yield, yield);
  }

  public Predicate({T => boolean} eligible, {T => boolean} yield) {
    this.eligible = eligible;
    this.yield = yield;
  }

  public boolean eligible(T item) {
    isEligible = eligible.invoke(item);
    return isEligible;
  }

  public boolean yield(T item) {
    return (isEligible && eligible == yield) ? true : yield.invoke(item);
  }

  /* Unchanged pre-defined predicates not shown here */

}

Applying the same correction to the original closureless version is not nearly as simple. It would require a more complex solution and could even involve changing the interface.

It is very interesting that polymorphic functionality can be achieved by injecting closures into one concrete class instead of defining multiple subclasses of an abstract class. Closures and anonymous inner classes, injection and inheritance, deferred execution and late binding. So many great choices!

Advertisements

Written by warpedjavaguy

September 4, 2008 at 11:31 pm

Posted in java, programming

Tagged with

Java Closures – The Fundamental Benefit


Avoiding redundant code is a basic programming instinct.
 

How many times have you written a piece of code and thought “I wish I could reuse this block of code”? How many times have you refactored existing code to remove redundancies? How many times have you written the same block of code more than once before realising that an abstraction exists? How many times have you extracted such abstractions successfully? How difficult was it to do and how much effort was involved? How constrained were you by the current Java language constructs? These are all questions pertaining to the everyday challenges we face as Java programmers in our struggles to achieve zero code redundancy.

Closures are reusable blocks of code that capture the environment and can be passed around as method arguments for immediate or deferred execution. Why do we need them in Java? There are many reasons for and against, but the fundamental benefit they provide is the facilitation of redundant code avoidance. The current Java closures specification makes a strong point of this in the first paragraph where it states: “they allow one to more easily extract the common parts of two almost-identical pieces of code”.

Closures provide an elegant means of reusing blocks of code and avoiding code duplication without the boilerplate. This is the fundamental benefit that closures bring to Java. All other benefits are derived benefits inherited from this fundamental benefit. In fact, all the needs addressed by the Java closures proposal are all derived benefits.

I know I am just stating the obvious and reiterating my point here, but it is just too easy to overlook this one fundamental benefit and be overwhelmed by all others. Java closures make it easier to eliminate redundant code and avoid it altogether!

Written by warpedjavaguy

June 25, 2008 at 10:32 pm

Posted in java, programming

Tagged with

Closure Syntax Wars


Closures look weird and complicated but so does all other code in general.
 

There seems to be some disagreement amongst the Java community about what the exact syntax for Java closures should be. The two currently most popular closure proposals are BGGA and FCM and they each use a different syntax. Neither syntax is final and looking at the discussions and comments in recent polls and many various blogs it is evident that we all have our own opinions, preferences, and personal favourites (myself included). And as developers why shouldn’t we? We are the ones that will potentially have to write and maintain code that uses closures. That’s why we care about the syntax.

The current BGGA proposal uses the ‘=>’ syntax. Although this looks like an arrow that points to a block of code, it can sometimes trick the eye and easily be mistaken for the ‘>=’ and ‘<=’ conditional operators. Consider the example below which defines a function that returns a boolean and accepts a parameter of type int and compares it against two variables.

{int => boolean} f = { int x => y <= x && x <= z };

Now consider the same example using the current FCM ‘#’ syntax. This style is designed to look and feel like Java method signatures. It is less confusing and easier to grasp though.

<ol>
  <li>(boolean(int)) f =  #(int x) { y <= x && x <= z };

In my previous post I questioned why we shouldn’t consider Java Method Pointers (JMP). The inspiration for this was a familiar but variant form of the C/C++ function pointer syntax. The same example would look something like this:

boolean* (int) f = (int x) { y <= x && x <= z };

Closures are indeed an alien concept to Java and they sure look alien too. Throw generics into the mix and they can look even more weird and complicated.Take a look at the following two examples:

Neal Gafter’s closures puzzler which transforms a list of objects of type T to a list of objects of type U.

static  List<U> map(List list, {T=>U} transform) {
  List<U> result = new ArrayList<U>(list.size());
  for (T t : list) {
    result.add(transform.invoke(t));
  }
  return result;
}

Stephen Colebourne’s evaluating BGGA example which converts an object of type T to an object of type U.

public  {T => U} converter({=> T} a, {=> U} b, {T => U} c) {
  return {T t => a.invoke().equals(t) ? b.invoke() : c.invoke(t)};
}

At the end of the day, we really want closures in Java for doing these nice things:

  • Simplifying anonymous class instance creation
  • Automating resource management/termination (ARM blocks)
  • Using for-each style loop constructs
  • Writing less boilerplate code

Closures would make it all possible. A lot of the complicated closure constructs involving generics would be integrated into the API. Developers would not have to write those. Java would provide them out of the box.

The more you look at closures and read about them the more familiar and less alien they become. Just like everything else, they do take a little getting used to. The question is what closure syntax do we want to get used to? Will it be good for Java? One day we may have to decide. Until then, the syntax war will continue.

Written by warpedjavaguy

February 28, 2008 at 12:14 pm

Posted in java, programming

Tagged with

Pointer Syntax for Java Closures


If Java closures are pointers to methods then we should make them look like pointers to methods.
 

Closures for Java are a hot topic yet again. The BGGA proposal is currently leading in the polls. It seems that most people who want closures want full closure support. I like the BGGA proposal, but I think the syntax can be improved to look more familiar and less verbose.

I generally tend to think of Java closures in the same way that I think of C/C++ function pointers (or member function pointers). A lot of programmers like myself transitioned from C++ to Java back in 1999. Java borrows a lot of the syntax from C++ and it was a natural transition for C++ programmers to move to Java. Given this, I cant help but question whether or not we should adopt the familiar C++ function pointer syntax for Java closures. That way the syntax (at least) would not be too alien to us.

Borrowing the examples from Stephen Colebourne’s weblog entry on evaluating BGGA, we have the following syntax comparisons:

BGGA syntax:

int y = 6;
{int => boolean} a = {int x => x <= y};
{int => boolean} b = {int x => x >= y};
boolean c = a.invoke(3) && b.invoke(7);
public {T => U} converter({=> T} a, {=> U} b, {T => U} c) {
  return {T t => a.invoke().equals(t) ? b.invoke() : c.invoke(t)};
}

Java Method Pointer syntax (simplified C/C++ pointer syntax for Java):

int y = 6;
boolean* (int) a = (int x) {x <= y};
boolean* (int) b = (int x) {x >= y};
boolean c = a.invoke(3) && b.invoke(7);
public  U* (T) converter(T* a, U* b, U* (T) c) {
  return (T t) {a.invoke().equals(t) ? b.invoke() : c.invoke(t)};
}

In addition to this, we could also borrow the & syntax and reference existing static and instance methods like this:

boolean* (int) a = class&method(int);
boolean* (int) b = instance&method(int);
boolean* (int) c = this&method(int);

If we want closures in Java, why not borrow the C/C++ pointer syntax and think of them as pointers to methods if that’s what they are? Most of the Java syntax is borrowed from C++ after all. I understand that function pointers do not fit well in the OO paradigm but I’m not talking about pointers to functions here. I’m instead talking about pointers to methods in the OO world of Java.

Written by warpedjavaguy

February 21, 2008 at 9:51 pm

Posted in java, programming

Tagged with

%d bloggers like this: