Writing Maintainable Code

time to read 9 min | 1719 words

Brian Kernighan said:

Debugging is twice as hard as writing code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.

Quite often I find myself rewriting parts of code that I written to make them reasable to a future me (that is without even starting to talk about other developers who may have to maintain my code). Consider the following code, what does it do?

foreach (Order order in approvedOrders)

{

    Order current = order;

    ((Proc)delegate {

        Context.OrdersDispatcher.DispatchOrder(current);

        SafeInvoke(delegate

        {

            Context.View.OrderDispatched(current);

        });

    }).BeginInvoke(delegate(IAsyncResult ar) {

        ((Proc)ar.AsyncState).EndInvoke(ar);

    },null);

}

It simply dispatch orders asynchronously and update the UI when an order's dispatching is completed. Of course, in this piece of code there are N + 3 threads involved (current thread, UI thread, end invoke thread?, how ever many threads may be needed to process the dispatching). I really don't want to debug something like this.

I may start out by writing similar code, enjoy the shear incomprehensibleness* elegance of the code, and then refactor it so it would end up looking like this.

foreach (Order order in approvedOrders)

{

    ThreadPool.QueueUserWorkItem(DispatchOrder,order);

}

 

public void DispatchOrder(object order)

{

    Order current = (Order)state;

    Context.OrdersDispatcher.DispatchOrder(current);

    SafeInvoke(delegate {

        Context.View.OrderDispatched(current);

    });

}

The functionality is the same, and I didn't refuce the burden of multi threading on the code, but just splitting it up to seperate method makes it simpler to look at the code and see in a glance what it is supposed to do. The scary part is that this is not even the least debuggable / comprehensible code that I have written.

*I actually got the spelling right in the first go, Wow!