We have all seen it, sitting there, waiting for code, when we first open a page in code view. The handy Page_Load(object sender, EventArgs e) method:
Well, friends, I am here today to tell you that this method is evil. That’s right, this nice friendly delegate is actually evil. And here is why:
- It encourages doing everything when the page loads by raw convenience. And doing all that inside this one method. I have seen 300+ line Page_Load methods on an alarmingly regular basis. I have seen entire websites programmed into Page_Load methods. Probably 95% of the ASP.NET code running in this world lives in a Page_Load method.
- It obfuscates page life-cycle from inexperienced developers. Too many just use Page_Load because that is the only way they know to get code to execute when a page is requested, save handling postback events.
- Page_Load is too late to do some things, like add controls, confusing some developers.
- Page_Load is too early to do some things, like deal with button clicks, confusing some developers.
- From a maintainability perspective, it makes it difficult to move actions into different places of the page-life cycle when necessary.
OMG! THAT IS EVIL! What am I to do!?!?!?!
So, you are not to use Page_Load, what is one to use? Well, one should just wire up page events manually in the constructor. Like so:
Why is this a the superior method? First, your actions can be logically grouped into their own methods, rather than having them live as 20 line segments of a monster Page_Load() method. Second, and most important, is that you can easily move a method around in the page lifecycle by changing the name of the event it is attached to. Finally, you are left with much cleaner, much more intelligible code.
Happy coding and it if you like it.