Wednesday, March 02, 2005

Contextual / Ambient support

Wouldn't it be nice if we had context support built into programming languages? Oftenly when you write code you have some object "X" that is almost global but not quite. You want all the calls from one point onward to use this value, but you can't make it static so you end up bouncing it around as an additional argument in all method calls. Like this:

method1()
{
X = something;
method2(a, b, c, X)
}

...

method5(r,X)
{
y = X.property
}

It would be much nicer to be able to set "X" as a contextual value in method1. A callee method could have a way to detect the closest parent context containing the value it needs, and get it. Like this:

method1()
{
X = something;
context.contextualX = X;
method2(a,b,c);
}

...

method5(r)
{
y = context.contextualX;
}

Here, the line
y = context.contextualX
would mean "find the closest context that has 'contextualX' defined and return that value". This would also mean that some method3 could override this value and set its own for its own callees to consume.

Ok, so this is something AOP guys already have (say, in AspectJ, although slightly different). But there is another aspect (pun intended) here: what about structural hierarchy? How do I make all child controls inherit their background color from the parent (windows programmers call this an "ambient" property)? This should be done in a similar way. Obviously, someone would have to tell the runtime that in this case control hiearchy is established using the Parent property found in the Control class, but that's all. Moreover, if we can do this, we can have multiple hierarchy types using different properties. So, to summarize, let's say we declare different context types, like this:

// a structural context using the Control.Parent property
context MyControlContext : StructuralContext <"Control.Parent">
{
int BackgroundColor;
}

// a call context
context MyCallerContext : CallContext
{
int contextualX;
}

We would use these properties as if they were static, and the framework would take care of finding and storing their values. So:

MyControlContext.BackgroundColor = this.BackgroundColor;
...
inheritedBackground = MyControlContext.BackgroundColor;

or

MyCallerContext.contextualX = somevalue;
...
y = MyCallerContext.contextualX;

Now, I suppose that this could be implemented in C# using attributes and reflection (probably in a similar fashion, too, in Java). But it would be painfully slow and ugly. What is needed is built-in support in the runtime. One day, maybe?

No comments: