Thursday, January 7, 2010

SqlQueryBuilder Model

Type based programming

My SqlQueryBuilder has an expression tree. The tree node could be ExpLeaf or ExpCompo that are subclass of Exp. I need to differentiate them. Originally I did:

if (node.ToType() == typeof(ExpCompo) && exp.Type != node.Type)
{...}

Where ToType() is defined in ExpLeaf and ExpCompo as following:

public override Type ToType()
{
return typeof(ExpLeaf);
}

You have noticed, I use "==" operator to determine if two type instances are the same. It works but looks stuborn. There is a more natural way to do it. I end up removed ToType method and use "is" operator:

if (node is ExpCompo && exp.Type != node.Type)
{...}




public enum RelOp
{
Equal,
LessThan

}

enum LogicOp
{
And,
Or
}

enum ExtType
{
And,
Or,
Leaf
}

public abstract class Exp
{
public string Type;
}

public class ExpCompo : Exp
{
public List ExpCompos;

}

public class ExpLeaf: Exp
{
string field; // Field field, may include type, CONVERT(DATETIME, value);
string value;
RelOp relOp;

public ExpLeaf()
{
//this.relOp = RelOp.Equal;
}
}


public class QueryBuilder
{
public void Build()
{
List exp = new List();

ExpLeaf leaf = new ExpLeaf();
leaf.Type = "";
exp.Add(leaf);
}

}

No comments: