Hitchhiker's Guide to Software Architecture and Everything Else - by Michael Stal

Sunday, January 09, 2005

Simulate Closures in C+ 2.0

For all C# developers and Java developers who are interested in leveraging generic data types I've implemented an example that illustrates the implementation of block/closure-like features in the aforementioned languages. Those of you familiar with blocks in languages such as Ruby or Groovy will certainly know what I am talking about.
The example implements a generic datatype Collector.

The C# code is as follows (Java would be very similar):

namespace CollectOperation {
public class Collector {
public delegate T CollectDelegate(T temp, T parm);
public static object DoCollect
(ICollection coll, CollectDelegate cdel, T initVal)
{
T res = initVal;
foreach (T elem in coll) res = cdel(res, elem);
return res;
}
}
}

The main method in the class is the static method DoCollect which expects a collection of values, a method reference (probably an interface when using Java), and an initial value. The method iterates over all collection elements, and calls the delegate for each of them. The delegate method (the method to which the delegate refers to) should support two arguments, the first representing a kind of aggregation value and the second the actual element the iterator points to. Both are of type T (the parameter type). The delegate method returns a new object of type T which is then used as the new aggregation value in the next call to the delegator.

Confused by the theory? To show you the idea consider that you are using a collection of integers. You are going to use the Collector to sum up all values in the collection starting with zero.

In this case just invoke Collector.DoCollect(valuelist , addDel, 0)
where the delegate method is public int Add(int res, int parm) { return res + parm; }

Want to concatenate all string in a string collection starting with a specific prefix? Then you the Collector parametrized with string and pass a mathod that concatenates strings.

Got the idea? Basically, you are passing a method as a block to the Collector method DoCollect.

As you'll hopefully agree, generic datatypes offer you some opportunities to implement really sophisticated features.

0 Comments:

Post a Comment

<< Home