When I made the move from classic ASP to ASP.NET back in 2003, one of the things that I was excited about giving up was having to put business logic on the same page as my presentation layer. In fact by that time, I was already in the habit of writing my ASP pages with most of my server-side scripting at the top of each page with as little as possible in my HTML. Once I got the vision of true OOP, my spaghetti code days were over ... so I thought.
It appears that a lot of ASP.NET developers are having a hard time letting go of the old days. For example, the web application used to maintain this blog site (BlogEngine.NET - highly recommend it!) is riddled with spaghetti code. And not just for referencing public variables from the code behind page, I'm talking about importing a class at the top of the web form and refering to properties and methods. Here's a sample of BlogEngine.NET using its BlogEngine.Core class to provide the Name and Description of my blog:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="site.master.cs" Inherits="themes_curiouslygreen_site" %>
<%@ Register Src="~/admin/menu.ascx" TagName="menu" TagPrefix="uc1" %>
<%@ Import Namespace="BlogEngine.Core" %>
<div id="header_inner">
<h1><%=BlogSettings.Instance.Name %></h1>
<div id="slogan" style="text-align: right"><%=BlogSettings.Instance.Description %></div>
</div>
I've already extended this code by taken out some of this in lieu of using the unused code behind pages. However, in doing so, I noticed some benefits that wasn't expecting from this old school approach:
-
Easy to Maintain. For simple web forms, using just the one page isn't a bad option versus having to flip back and forth from your Design and Code view.
-
Less code. Not having to deal with the code behind page has been an unexpected benefit. Why create a bunch of label or literal controls to display properties from a class if you can just specify them directly in your web form?
-
More Readable. One thing that made sense about classic ASP was that it was clear what elements were static and where your HTML was going to be dynamically generated. So far, it's been very easy to read and understand this way of coding web forms versus dealing with a lot of web server controls that look like HTML.
-
Logic still separated. You'll still create your classes to hold your business logic, you just save the effort in the code-behind.
Bottom line - ASP.NET doesn't mean the end of spaghetti code after all; as long as you stay true to OOP concepts, it just means you can write it cleaner. However, make no mistake, this does not mean the death of the code behind - far from it. I simply learned that I don't have to always shy away from putting server code in my web forms. Expanding my horizons (as they say) ... going outside my shell. You should try it sometime.