The Thing About ExpressionVisitor 16 Dec 2008


Brouillard There was a discussion recently about why the class ExpressionVisitor, which every programmer that developed a LINQ provider or code manipulating .net 3.5 expression trees knows about. I certainly agree that this class could have been made public, as basically everyone ends up embedding it. Even if it could use a little refactoring to visit lists. Thing is that I have a naming issue with this class ever since I saw it on Matt's blog. To me it does more than just visiting an expression tree. It allows you to transform it. And when I'm facing an expression tree, I often like to sometimes visit it, and at some other times, transform it. That's basically the reason why I have both a:
class ExpressionVisitor {

    public void Visit (Expression expression)
    {
        // ..
    }

    // ...
}
And a:
class ExpressionTransformer {

    public Expression Visit (Expression expression)
    {
        // ..
    }

    // ...
}
Simply because I write a lot of code that would look like:
SomethingExpression VisitSomethingExpression (SomethingExpression expression)
{
    if (Foo (expression))
        return expression;

    if (Bar (expression))
        return expression;

    Baz (expression);
    return expression;
}

And it looks a lot better (and is also a tiny bit faster) this way:

void VisitSomethingExpression (SomethingExpression expression)
{
    if (Foo (expression))
        return;

    if (Bar (expression))
        return;

    Baz (expression);
}
So if they make the current ExpressionVisitor public, having a real non transforming ExpressionVisitor will introduce an interesting naming issue. I submitted a bug to the DLR CodePlex, as the namespace System.Linq.Expressions will come from the DLR in .net 4. What about voting for it?