Spaghetti, CodeInPage, CodeBehind, and CodeBeside

 Now that Whidbey is around, I think it’s a good time to reflect on all these different coding models we’ve used over the years.

Way back in the asp3 days, we had two basic but not-mutually-exclusive ways of putting our code into our page. The first version most people learned is the spaghetti code style. This is where you just have your html as you always did, and in the document where you wanted dynamic html, you’d put a <%=  %> block, and just emit some html. This was easy, quick, dirty, and horrible. Long term, this style is very bad for disciplined coding and maintenance. The other method was to put code in a separate script block element that was set to runat=”server”. This style doesn’t have a real name, so I’ll call it CodeInPage for this, but was much better in many ways, but probably the best win was that the logic was in one place and the presentation was in another. Unfortunately, the basic asp3 infrastructure didn’t really provide a lot of tools to help you write code this way. Many people wrote their own frameworks on top of asp3 to support this separation and while they worked, I never saw a single one that really felt “right”. Most used xml/xslt or COM based UI objects. And because these frameworks were fairly complicated, it was a hard sell to the new guys just learning asp3. Spaghetti was just way too easy and obvious for simple examples.

And then came out and everything changed. Now we had a new layer on top of the basic request/response streams. We had serverside controls that we could manipulate with code in it’s own block. It was much closer to the  Form/Controls model that has proven so useful in both windows applications and which has existed on the browser clientside with elements and javascript. So now the spaghetti style, while still around, was obsolete. And beginners could really get into the dragging of controls onto the designer and handling button click events. It was natural and quick.

So what are the options now? Well, there are two. The CodeInPage model and the new CodeBehind model. We’ve already talked about CodeInPage, and for those who don’t know (who are you and why are you reading this blog?), CodeBehind is where there is a separate file for the code. This file derives from Page, contains declarations for the server controls, and contains all the event handlers and such. The aspx file then derives from this class for the final page. Which one to use here has been a pretty big issue since was introduced to the world way back when.

So here is where I get into some serious minority opinion, but hopefully people won’t dismiss it just because it’s the minority right now. Up front… I think the CodeBehind model is a bad hack. CodeBehind solves two tool-related problems while bringing in a whole host of other framework-related other problems. The two problems that CodeBehind solves is that intellisense needed 1 language per file to work, so the serverside code was put in one file and we are happy. It also eases the compiler pain of detecting bugs in serverside code, as it only needs to deal with the code files by themselves, not the ui declaration mixed in. However, look at the problems it creates…

·        While the codebehind is compiled, it is never checked against the aspx declaration, so any disconnects there, such as malformed DataBinding syntax areas, or mismatched IDs, or any host of other problems, won’t be known until runtime when somebody hits the page. But you get this misleading feeling that everything is ok because it compiled ok.

·        Take a hard look at the interaction between the CodeBehind class and the aspx Page class. The CodeBehind class contains control declarations and event handlers, but it never instantiates the controls. The aspx derives from the codebehind, also contains the same declarations, these declarations are hooked up by apparent magic, and actually instantiates the protected members of the base class. I don’t know about you, but if I saw somebody follow this pattern in any other context, I would be appalled.

·        It’s a bad application of the “separation of code and UI” concept. In general, seperation is a good idea. It is a bad design to be running sql commands from your button click event handler. However, this goes both too far and not far enough when it comes to code behind. Look, the code that interacts directly with the UI is forever linked to the UI. There will never be a true separation between a Panel declaration and the code that says MyPanel.Visible = false. And at the same time that you have this over-seperation of the code and UI, you also have all this code in the UI declaration file, disguised in databinding syntax blocks. Obviously the bulk of your app code should reside in non-UI assemblies. Business layer, Data Layer, etc… but right at the edge, where the UI needs functionality, there needs to be some code that ISN’T separated.

Now I’m not saying that CodeBehind is all evil, it’s great for what it does, which is give you better tool support. I’m just saying that these bad things only exist in order to have a tool that has to be worked on less to offer more features and thus sell better.

The pros and cons for CodeInPage are exactly the opposite. No vstudio support for things like a design surface that you drag controls on to. No intellisense in your code. No pre compilation for error checking. But the model, it seems to me, is more correct. It’s the tool that is not finished. The model here is better because everything in a page gets compiled to one class. The fact that the UI is declared in a different language than the what event handlers are coded in… seems rather irrelevant to me. Nobody seriously spazzes about a windows.forms app having the UI declaration ( Do Not Edit Me region ) and the form code being compiled to the same class. As far as I can tell, that’s only because they are in the same language. I don’t have a problem, one way or the other, as far as separate files for UI code and UI declaration is concerned. But the two are inexorably linked, and should be in the same class.

This point of view only really effects me in that I don’t have intellisense in my UI code. I wouldn’t use the designer in vstudio 2002/2003 anyway, because it borks the markup so horribly. And I don’t mind not having a designtime compile step for the UI code, as it’s not a whole lot of code anyway. The dynamic compilation feedback and debugging support in is great as it is already. I don’t need to create some overly complex “web project” to build my site. I need a couple coded application tiers in its own solution, and a series of pages that use them.

So now Whidbey stuff is shown… and they’ve gotten rid of all the problems in both models. The tool now completely supports the CodeInPage model, intellisense and all. And the CodeBehind model has been morphed into the CodeBeside model, where the two are compiled into the same class. All the synchronization and odd design anitpattern problems just float away. So now in Whidbey, there is zero technical reason to choose one over the other. Now it’s just a matter of… do I like my code in a separate file? Or do I prefer my code as a separate view on the same file?

Personally… I like the single-file style still, if only for ease of copy-pasting examples to others and having a smaller file set to deal with. But the decision is so pointless, that I hope this whole discussion will just fade away.

So ya, that’s my take, and I’m sure I’ll get flamed to hell for it… but hey, at least consider my points before you laugh and set the bozo bit.


  • I think you missed one of the CodeBehind advantages, which, IMHO, is the most important one. When writing with CodeBehind, you can split the development phrase. Give the graphic designer the aspx file to toy with, and write the appropriate aspx.* code behind file. When the desginer will be done with his magic - just put it together and let it run.

    In addition, I don't think the Code Behind model was ever meant to be a Code - UI separation model. The BL part must reside in a seperate class, and not in the code behind file. The code behind file is not reusable, is bound to the aspx file, and is descendant of the Page class, which is not exactly the right choice for BL.

  • No flame here, I pretty much go along with everything you say - apart from the single file coding stuff, but that's mostly down to the architecture I tend to use (oh and I am phenomenally lazy and need intellisense to prop up my dismal memory). Partial classes do just seem so natural in VS.NET 2005. I still prefer to have seperate files but again, probably just me.

  • i agree...codebehind has always felt like a full-o-bugs hack. I'm often annoyed at some of the runtime bugs it causes (id's not matching) and in my mind thinking VS.Net should have caught those at compile time.

    What's more annoying is people who don't understand the the ASPX page inherits from the .cs/vb page (ie, they think the magic keyword is CodeBehind instead of Inherits) and can't figure out what the problem is.

    I think you might be impressed with how the ASP.Net Forums version 2.0 have done the separation (basically using skins and views). Its a good approximation of what we'll have in whidbey.

  • &gt;I'm often annoyed at some of the runtime bugs it causes (id's not matching) and in my mind thinking VS.Net should have caught those at compile time.

    that's because currently .aspx page is not parsed and compiled until that page is requested or in another word, at runtime. dunno if whidbey is treating compilation of partial types any differently in this case or not.

    and to Andy, I think the aspx and codebehind seperation is not intended to be a seperation of layers, but rather a seperation of the MVC pattern. where the aspx is the view, codebehind is the model, and the framework, the controller, does most of the job to glue the two together.

  • Don't forget another model that ASP.NET brought to us: AllCode. No ASPX files, baby!

  • And I thought I was the only one who got horrified by the HTML VS.NET creates. It even doesn't understand XHTML (neither 1.0 nor 1.1) and CSS 2 completely. A truly horrible tool for a developer who focusses on building Web applications based on Internet standards or do you pave streets in a way that only a Ferrari can drive on it?

  • The XHTML stuff is WAY better in VS.NET 2005 - lets you select schemas, validate the lot!

  • Well, it's about time, no? ;-)

  • This is how I've felt from day one. The CodeBehind model in 1.x just isn't a good fit for most cases.

  • This is how I've felt from day one. The CodeBehind model in 1.x just isn't a good fit for most cases.

  • Memi - I've heard the argument about &quot;separating development effort&quot; between UI designer and coder (and I might have used it when VS.NET first came out), but do you REALLY ever do that? Do you really have one person build the ASPX and a different person build the CS file? That would surprise me, because even though they are separate files, I think they are pretty tightly bound to each other.

  • Josh.

    I actually use that model on a daily basis. We have me, the developer, and a graphic design dude. I can't come even close to the magic he creates. And, he can't even comprehend what I do.

    They are only tightly bound in that, by default in VS.NET, they share the same name.

  • You want .cs seperate from the .aspx for the same reason good web designers create external .js and .css files for their pages. It encourages proper structure, encapsulation, code reuse, and so much more.

  • but you don't end up re-using the controller code in the code-behind. The code you want to re-use ends up in a separate class usually, either as a static &quot;helper&quot; method or as an instance method.

  • I agree in that code-behind is broken because it only half-compiles prior to runtime, but I disagree that CodeInSide is a better answer for all of the reasons mentioned above.

  • I have to add my sceptism to the &quot;designer editing .aspx, developer editing .cs&quot;, but I might just be sceptic because the load of designers I've ever had the pleasure to know, have known far less about HTML, CSS and web standards than myself.

    Not that I'm an expert, but it's just insanely unrealistic to me that a web designer, who knows Adobe Photoshop like the palm of his hand, and digs DreamWeaver as much as free beer (no, that's not possible, I know) will ever be able to create good HTML and CSS. It just won't happen.

    Yes, I'm extremely biased, but it's based on my experience. What I tend to do, is rather have the designer hack around in DreamWeaver, Photoshop and whatever, send me the gritty pieces of code, and I deconstruct it and make it purty, validating, and hopefully looking the same as the designer wanted to (though without all the pixel masturbation).

    I'm looking forward to the next version of VS.NET, and to the validating stuff that comes with it. What interests me now, is if Microsoft will ever fully understand what the table tag really is supposed to contain, or if it will always remain as the number one design element in all markup created by the company in all times forever and ever.

    I.e.: will they learn to use HTML for semantics and structure, and CSS for visual ornamentation, and will VS.NET support this separation fully? And what validating scheme will VS.NET be set to by default?

  • I can certainly say that in my years as a web developer, I have written my fair share of spaghetti code in ASP 3.0. At some point at a former company, it became a general understanding that spaghetti code (or more specifically, the use of &lt;%= %&gt;) in ASP 3.0 files was slow. So we started to write pages that Response.Write()'ed all the HTML to the browser. Ok, so it worked, everything was in code, and we felt like we accomplished something. Furthermore, we used an inordinate amount of include files with routines to output every possible combination of &lt;TABLE&gt; tags imaginable.

    With the advent of ASP.NET, I took a more elitist attitude, and said to myself, to use &lt;%# %&gt; in an .aspx was totally and utterly ridiculous, that is what codebehind is for, and shame on me if I use it. Now, see what it takes to DataBind a DataGrid with template columns and not use a DataBinder.Eval statement. Guess what? It's a bitch. Rethink attitude.

    Ok, so the &lt;%# %&gt; construct isn't soooo bad, I admit it (freely and in polite company), but there must be a smoother way. Someone before mentioned the concept of zero markup output. I make it a rule that if a page doesn't emit HTML (e.g. dynamic graphics or a dynamic PDF), I use an HttpHandler and not an .aspx page. Also, any complex HTML manipulation is done in codebehind.

    I'm not an expert, and don’t present myself as such, but I have to agree with Andy in that there needs a to be tighter cohesion between the HTML markup and the code required to manipulate it.

  • I think &lt;%# %&gt; is an as ugly hack as the codebehind. Maybe even uglier. It might not even be a hack, someone thinks, but nonetheless; it's ugly. Maybe it will look and feel nicer in Whidbey when all code inside &lt;% %&gt; are intellisense'd and stuff, but it won't help much. It still feels wrong.

    Hence, all my programmatic output in every databinding (and non-databinding, for that matter) context is emitted through serverside controls which I either just place on the page (in non-databinding scenarios), or &quot;load&quot; using the FindControl() method. &lt;% %&gt; in the .aspx file makes me shudder.

    I have to agree with you, DrFooMod2, about using HttpHandlers instead of .aspx pages for non-textual output, though. And I think things will get better (in regard to codebehind) with partial classes. I really do.

  • Very interesting post. I was so fired up about getting rid of the old ASP &lt;% %&gt; code model that I didn't focus on the problems with code behind. In fact, when I first got Whidbey, I freaked out about the default &quot;code-beside&quot; model. The more I think about it and use VS 2005, the more I think it will be a welcome change.

  • I like &lt;%# %&gt; a lot. I restrict its use nearly exclusively to properties of the code behind page. It enables me to think of the code-behind as the data source for the ui and allows the code-behind page to not have to know about various little labels, etc. that I might otherwise poke data into during Page_Load (MyLabel.Text = &quot;foo&quot;;)

  • I can't believe how many people cannot spell &quot;separate&quot;!!!!!

  • Personally, I try to avoid code-inside as much as possible. Having deveveloped huge corporate sites with the &quot;classic&quot; ASP 3.0, I've inherited, and continued to hack at, some horrible spaghetti code that required a steep learning curve to understand completely. It was not pretty ... the .NET code-behind was a blessing, though not without it's own issues, as pointed out here.

    I'm not particulary familiar with Whitdbey ASP.NET features, namely the code-inside or code-beside model. I just hope that it will combine the relative abstraction of UI from logic and provide a way to navigate the code-inside much like it is posibble in the code-behind today. You know, the beautifull collapsable regions, intellisense, go to definition/reference functions, navigate back/forward etc. etc. etc. ... the stuff that makes code navigation a snap. Otherwise, the good old days of structural ASP 3.0 coding will come back to haunt us all, and believe me, I certainly don't want to go back to that ... I love my object oriented web development too much ... I'd rather switch to Java, and hack around with that language &gt;8P


  • Ireney, it seems like you didn't even read my post.

    &quot;CodeInside&quot; is NOT the same as spagehtti code. The whole asp3/spaghetti versus argument is a false dichotomy.

    Everything you mention as a strength of codebehind are IDE issues that are fixed in whidbey.

  • &quot;Way back in the asp3 days, we had two basic but not-mutually-exclusive ways of putting our code into our page. The first version most people learned is the spaghetti code style. This is where you just have your html as you always did, and in the document where you wanted dynamic html, you d put a &lt;%= %&gt; block, and just emit some html. This was easy, quick, dirty, and horrible.&quot;

    Perhaps I misunderstood your words, but it seems you clearly state that ASP3 CodeInPage or CodeInside lends itself to spaghetti code. While it is NOT the same as spaghetti code, the two seem to accompany each other more often than not. And I do feel that the current code-behind model, while certainly not perfect as you explain, does alleviate some of the issues that plagued ASP3 development, and lends itself to cleaner, much more object-oriented code.

    Using ASP3 CodeInPage type development as an example, I voiced my concern that perhaps CodeInPage model in .NET may become just as messy. Great to hear that Whidbey takes care of those issues.

  • I have to say that I agree with you. I've developed some pretty large web applications and in my experience, code behind has not been the &quot;Spaghetti Code Savior&quot; it's been touted to be. It takes developer discipline to prevent spaghetti code. Without it you just end up with a bunch of business logic and spaghetti code in the code behind file. I've seen some mighty horrific code behinds!

    To me, the code that is in the code inside/code beside/code behind should be nothing more than wiring code. In which case it shouldnt matter where you put it.

    The location of the code does not create spaghetti code, developers do.

  • Добавлю в закладки, интеретсно читать

  • Sharp tools make good work.


  • -----------------------------------------------------------
    Your blog is so useful … retain up the excellent perform!

  • -----------------------------------------------------------
    Remember to, can you PM me and inform me few much more thinks about this, I'm truly admirer of one's blog...gets solved properly asap."

  • I think this is one of the most important information for me. And i'm glad reading your article. But wanna remark on some general issues, The web-site style is terrific, the articles is genuinely good :D. Excellent job, cheers.

  • hello my beautiful world
    hello everyone on this place!
    i am Kate

  • Limiting the number of toys available at any one moment, and having a place for every toy, helps with the task of teaching the child to put toys away. In this short article you're going to get a list of my top 10 best selling toys for Christmas 2011. Now you can be a mighty Transformer and fight the Decepticons.

  • Nothing is over for someone who is alive.

  • We can boast of the fact that the toy car or the toy rail set we got as a gift on our tenth birthday is still functional even though it adorns a mantelpiece, but can we assure the fact that our children will be able to boast the same, ten years down the line in case of your gift? After all a toy is more than just a toy to a kid. Whenever you end the occupation you'll be able to definitely see a wide smile full of admiration and pleasure on your kid's encounter that could not be replaced by anything in this globe. Cool t-shirts to go with her denims or with her leggings are a must for her wardrobe.

  • 50 % discounts on all airtickets flights and hotels as well as all football matches
    email us at

    no advance payment needed

Comments have been disabled for this content.