Search code examples
c#lambdarefactoringmoqexpression-trees

Cleanest way to define an expression tree?


Consider the following three lines of code which are part of a unit test:

var order = new NewOrderSingleTestMessages().ValidMessage;

Expression<Func<ExecutionReport, bool>> expectedReply = r => r.OrderID.Obj != string.Empty && 
                                                             r.ClOrdID.Obj == order.ClOrdID.Obj &&
                                                             r.ExecID.Obj != string.Empty &&
                                                             r.ExecType.Obj == ExecType.NEW &&
                                                             r.OrdStatus.Obj == OrdStatus.NEW;
                                                             // a lot more conditions are required here!

// ...

processorMock.Verify(m => m.Process(It.Is(expectedReply), It.IsAny<SessionID>()), Times.Once);        

Ugly! Also there are going to be a lot more conditions in the future. How can I refactor this in a more clean and clearer way?


Solution

  • Well, I often write returned chained conditions like:

    return a == b
        && c == d
        && !d
        && foo(e, f)
        ;
    

    or …

    return a == b
        || c == d
        || (!d && foo(e,f))
        ;
    

    I guess the idea is clear.

    However, that's pretty when returning something, not in an if statement, or as like you're doing. It wouldn't feel right to make a function just to return pretty trash if you never would use that function again - in my opinion. However, it could be more readable...