sabato 14 agosto 2010

JFK: implementing a raw yield return

A new feature has been added to JFK: a raw support for the yield return.
Before explaining it, please consider the cases when a yield return is useful: you are iterating over an iterator and want to return, one at a time, the next value extracted from the iterator.
Consider the following method:

public int cycle(){
    for( int i : this.myIterable )
        return (i*i);
    return 0;

Now, supposing myIterable is an integer iterable that returns numbers from 0 to 1000, the above method does not cycle on all the values, but returns always the first element in the iterator (so it is 0). The adoption of yield return allows the iterator to return the next value each time the method is called.
At the time of writing, JFK supports yield return when using iterators, and to get this support developers have to:
  1. use a class-level iterator (i.e., not in a local method scope);
  2. annotate the iterator with the @Yield annotation to inform JFK that the adoption of such iterator can be yielded. Since JFK must have access to the iterator, in the case the latter is private, developers can indicate in the annotation a get method for the iterator itself.
  3. ask JFK to build an instance that exploits the yield return.
The important thing to note in the above duties is that no special bareword or special objects must be used by developers: the methods are written as in normal Java. 
So, taking back the above cycle method example, supposing the myIterable
object has been annotatoted with the @Yield annotation, the following code will produce a progressive output:

IYieldBuilder yBuilder = JFK.getYieldBuilder();
// GoodYielder is an objet with the cycle method
GoodYielder gy = (GoodYielder) yBuilder.buildYielder( GoodYielder.class );
for( int i = 0; i < 10; i++ )
     System.out.println("Cycling with yield: " + gy.cycle() );

will produce

        Cycling with yield: 1
        Cycling with yield: 4
        Cycling with yield: 9
        Cycling with yield: 16
        Cycling with yield: 25
        Cycling with yield: 36
        Cycling with yield: 49
        Cycling with yield: 64
        Cycling with yield: 81
        Cycling with yield: 100

The current support to yield return is really minimal and useful for a limited set of use cases. I'm currently investigating a more complete and general approach, keeping into account that no syntactic or semantic overhead will be introduced: the yielding must be declarative!
In the meantime, if you need a more complete yielding mechanism (which is very different in syntax and semantic to JFK aim) have a look at Java Yielder here.

Nessun commento: