Friday, May 15, 2009

ASPX, CreateChildControls, Sequence, Abstraction, and Lazy Evaluation

So one thing I have noticed when working with ASPX is that you get a lot of bugs because things are done out of sequence. One of the primary culprits is CreateChildControls. Why is this such a problem generator? Because depending on whether you are posting back on not it runs at a different time. Normally it runs after OnLoad, but on postbacks it runs before OnLoad. So you can get very different behavior for postbacks for a non-obvious reason.

There are a couple ways around this. One, don't put stuff in CreateChildControls that doesn't belong there. As per the name this functions for control creation, not random junk. Also, if you need access to something dealt with in CreateChildControls call EnsureChildControls.

Now I want to mention two forms of abstraction. Model-View-Presenter and Lazy Evaluation. Lazy Evaluation is an awesome pattern to use in webpages because you don't always have a clear view of the sequence and this pattern removes all sorts of problems you would normally run into. I highly recommend this pattern. Currently at my work we use MVP. MVP breaks up code into functional layers and in my experience can often conceal sequence issues. Once you go past the familiar order of OnInit, OnLoad, Control Events, OnPreRender, OnRender, and OnUnload you get into a nebulous realm where you just aren't sure what is happening when, and that is dangerous.

Now some people might be thinking loading a web page is somehow event based. And .Net does a good job trying to sell you that it is. But that is just not true. A page has nothing in memory and no state. Then there is one big event, page load, and then you are done. Sure there is an event mechanism, but a web page load is fundamentally different from a program that has state and randomly receieves UI events. A page load constructs everything in memory, process any interesting data sent in s POST and then constructs a response.

Anyway, my point is that correctly sequencing things in ASPX is actually pretty tricky and is easy to do wrong, especially if you pile the wrong kind of abstraction on top of your pages.