.Net and my wrath against Code Behind
Categories: IssuesI’ve been unusually busy these last days, doing both studies (master of technology management. Yes, doing my second masters) and a high-paced project counting 9 developers and a project manager. This project is developed done in Microsoft.Net 2.0. Definitely a two-headed monster situation.
The thing about .Net projects is the ease of coding directly towards the web interface. Simply add a grid in the markup (i.e .aspx) file and name the fields you’d like to display. In code behind, add the datasource you use to the grid and bind it. Job done! The simplicity of it is almost magical. However, the evil twin head won’t show up before you actually has to do something more than simply binding data.
For what happens when a button is pressed and the business logic is triggered? Or what if the datasource data need to be interpreted before displayed? What if the grid needs to be summarized? Or if my grid needs to be a combination of two datasources? Here comes the custom code and the custom code tends to end up in the code behind file. The result? Spaghetti code. And not anything tasty either.
In other words, despite .Net is absolutely object oriented and has a great bunch of tools, the greatest benefit (code behind) can suddenly transform into a application maintenance’s worst nightmare. Because first and foremost .Net is Code-Behind-Driven and the ease of putting the custom code there is simply to great for developers to resist.
My wish to you all: avoid custom code in code behind. Think about it this way: if it’s not testable through unit tests, it should be refactored. Object-orientation can be used to think of each displayed item as an object, with a set of values and behaviour. Services can be used to separate business logic. And presentation logic can be extracted from the code behind into natural objects.
Avoid coding straight into the events. Avoid storing values in session or viewstate and retrieve it in the middle of a method or event handler. Thank you