Hanalei, Hawaii 9/2/2010
438 Posts and Counting

Crazy Talk: Inline Scripting and Code-Behind

Monday, October 15, 2007 -

As if I haven't been flamed enough in the last few days (and I still have a few minutes left on my Fire Ward), I'm going to challenge the notion that Inline Scripting is a relic of Web 1.0, and that it has no place in today's ASP apps. I take a slightly different view, and that is that many times inline scripting is preferable because it forces you to write less UI code, decreases ViewState abuse, and can result in cleaner, more manageable HTML.

Inline scripting gets a bad wrap in the ASP world. Many people avoid it like the plague and you're branded as a "Spaghetti Hack" who "codes like it's 1999". I've stared, open-mouthed, at these words in the SubSonic forums as people have questioned my preference for inline scripting. I've been meaning to write this post for a while, and this weekend I've finally had the chance since the inlaws are in town :).

I like what Atwood has to say about it:

After religiously adhering to the new, improved code-behind model of ASP.NET for so long, I have to admit it's sort of refreshing to rediscover inline code ASPX pages again. Deploying single web pages to a server without recompiling the entire solution? Making localized edits to single pages that take effect in real time? A single file that contains both code and markup in one convenient self-contained package? Revolutionary!

but then he finishes with this:

Unfortunately, Inline ASPX pages also remind me of some things I didn't miss from the bad old days of ASP programming: spaghetti code, extremely limited intellisense, and crappy debugging

That post was written in 2005. Today, however, with Visual Studio and ASP 2.0, we now have great debugger support in the designer and intellisense so that mitigates a lot of concerns that people have. In terms of Spaghetti Code...

Spaghetti Code
It's not easy to write spaghetti code using .NET, but there are many who manage to do it. From Wikipedia:

Spaghetti code is a pejorative term for source code which has a complex and tangled control structure, especially one using many GOTOs, exceptions, threads, or other "unstructured" branching constructs. It is named such because program flow tends to look like a bowl of spaghetti, i.e. twisted and tangled

So Spaghetti code makes it hard to understand what an app is doing during execution. I think this is more a function of what ASP's CodeBehind model allows you to do, versus the concept of "scripting the UI". Spaghetti is as Spaghetti does...

In purest terms, scripting the UI should literally be a visual expression of logic, NOT the logic itself. To that end, simple, VERY SIMPLE routines in the UI are acceptable (and needed) when scripting. This is an important aspect of this discussion: Logic does not belong anywhere near the UI!

Rails has some neat guidelines to follow when working up their views:

  • If you declare a variable in your View, you're doing something wrong. This suggests logic and you should use a helper or your controller.
  • Data Access is the UI is verboten.
  • If your eRB (the Ruby code in the page) is more lines than the HTML, you're doing something wrong

To dive into this further, let's use the ubiquitous GridView example. For fun, let's see what it takes to do something simple, like link to an editor page from a grid. I'm using Northwind, SubSonic, and ASP 2.0 Web Site for this example.

GridView with ObjectDataSource, bound to Products.Fetchall() - a BLL method

gridviewsetup

The designer makes this trivial- I just hook up the ODS to ProductController.FetchAll() (using SubSonic) and I'm well on my way! Not one to be fooled by a designer's simplicity, let's take a look at the markup:

gvmarkup

Let's hook up the select events. Here's the code:

selectCode 

Now let's do the same thing using inline-scripting (the Controller in this example is my BLL):

inline

So consider:

  • There's about 1/3 of the total code with the inline solution
  • You can read and grok what that page is doing in one glance
  • Complete control over the HTML
  • No ViewState
  • No recursive control tree loads/parses, making the page faster...
  • Easy to debug (since ASP 2.0 allows you to debug in the designer)
  • Yes, you DO have intellisence :)

I need to keep my HTML and Code Separate
Why is that anyway? Designers use Photoshop, and think in terms of PSDs. Designers don't use Visual Studio (I think it's a rule in SOMA that you have to turn in your Mac if you ever look at the Visual Studio's Medusa Glare [the white screen of pain when it stalls]).

You might be one of the lucky people on the planet who's workplace hires an HTML gunslinger (I've worked on 3 projects like this). These guys are usually the mock turtleneck-wearing guys who hang out by your desk trying to learn to code :). These guys know Visual Studio, but also know "runat=server" and "<%" means "don't touch".

Inline Scripting Is Slower
Not at all. From Jeffrey Palermo:

My colleague insisted that script block incur and extra performance hit because the ASP.NET engine must check for changes in every page hit.  After lunch, I whipped up a test and created to ASP.NET pages:  one with code-behind, and the other with the code in a script block.  I ran each for 1 minute in WAST.  Then I ran each 8 more times.  My results:  It doesn't make a hill of beans difference.  Each test was less than 1% difference

Inline Scripting Is Ugly
If you ask me, XML is ugly. Code is wonderful. I can read code easily and I (usually) can grok what was intended, Declarative markup (which is XML-based) just sits there, telling me nothing. This is subjective anyway and you can always toggle script blocks shut.

Only Hacks Use Inline Scripting.
Could be true, but if you take a second to look over the walls of the MS Schoolyard you'll see the kids playing with all kinds of code-based markup. Rails, PHP, Django - all use this style of programming. It's effective, and actually breeds LESS code (see below). The most popular platforms in the world... I'm hoping you're at least considering this by now...

Here's a virtual beer :). We'll make it through the rest of the post together...

Inline Scripting Breeds Crufty Pages That Are Hard To Read
It absolutely can, but often the issue is not with scripting as a practice, it's with the developer's coding style. Spaghetti is as Spaghetti does. If you drive yourself to rip out any logic from your UI, scripting becomes enlightening and fun.

If you're a Server Control Junky (use Image Controls, Hyperlink Controls, etc) I would ask you to consider whether the use of these controls (when not using skinning or required eventing) is warranted. Consider the Page Life Cycle:

  1. Start: Request and Response are loaded. IsPostBack is determined
  2. Init: The ViewState is decrypted, the control tree is created and parsed. Themes are applied (if present)
  3. Load: All settings are applied using the ViewState settings (if IsPostBack)
  4. Validation: Any and all validators go off
  5. Eventing: If you've called an event, it's fired
  6. Rendering: ViewState is recreated, walking the control tree (all setting are encrypted and dumped into a hidden input). In addition, each control's "Render()" method is called, and the HTML is created from the control stack.
  7. Unload: GC and cleanup

Generally, this stuff is pretty quick and you don't need to worry about it's execution. But if you don't need it to run at all, why do it? I'm not saying server controls are evil - I'm saying you should carefully consider whether they're needed.

With code behind, you get a big rug that you can sweep your code under. It can lead to bad habits (like too much code) and also cause slow downs that just aren't needed. 

CodeBehind 2.0
I think it's time to lean harder on the notion of UI scripting as just that: visually representing logic. CodeBehind is (most of the time) overkill for this . When .NET was introduced this seemed like the way to go (cause they told us it was). Now that it's 5 years later, it's time to revisit this notion - especially in light of the new MVC framework that's right around the corner.

Do you really need two pages, when one will do just fine?

Related


Gravatar
Joris Kalz - Monday, October 15, 2007 - I love beautiful cars, I love beautiful girls and I love beautiful code! That's the reason why I hate Inline Scripting! Yes, it is so ugly and it reminds me of my dark vb.asp-php-zope time writing crap stuff. Are you defending Inline Scripting because you are using it in your subsonic template engine?

By the way, in your code example you compare apples with oranges: instead of using the "SelectedRow" event you should use an "ItemDataBound" event to create the hyperlink. This would be more or less the equivalent to your Inline Scripting example.

One final think: I love subsonic, keep up your great work!
Joris
Gravatar
Rob Conery - Monday, October 15, 2007 - @Joris - come on! You can do better than "crap stuff"! Gimme something to chew on... The template engine has to use scripting cause it's a scripting engine :p. Same amount of code for ItemDataBound - I could also have used a Template - same amount of code :) but slower.
Gravatar
kevin - Monday, October 15, 2007 - wow, didn't know I was an HTML gunslinger or wore mock turtlenecks. I actually think I'm offended ;)
Gravatar
Megha - Monday, October 15, 2007 - Hi, I like inline code, I think its just keeps the logic tidy and code simple :)
Thanks,Megha
Gravatar
Kevin Dente - Monday, October 15, 2007 - In fairness, the overhead of managing viewstate is miniscule compared to refetching the data from the database, so in postback scenarios it's generally a performance win. For intranet apps, the bandwidth overhead of viewstate is negligable - who cares about a few extra K at GB ethernet speed? On the internet, of course, it's another story. I agree, though, the pendulum swung too far the other way with ASP.NET, avoiding inline script at all costs. Typical developer overreaction to intermingled biz logic and rendering logic in classic ASP. You're spot on, with the release of the MVC framework the pendulum will be swinging back the other way - inline rendering logic will return to the view. I'm dying to get my hands on it.
Gravatar
Rob (not connery) - Tuesday, October 16, 2007 - "These guys know Visual Studio, but also know "runat=server" and "
Gravatar
Haacked - Tuesday, October 16, 2007 - What many forgot is that the pain of classic ASP and the "spaghetti" code was due to mixing business logic with the presentation logic, not due to inline scripting specifically.

Sure, inline scripting just made it easy to mix the two, but ASP.NET did a decent job of making the separation more clear.

But again, there's nothing wrong with putting presentation logic as inline script.

After all,

">

isn't really (except for the data binding) different from



They're just alternative template syntax for the same thing.
Gravatar
Haacked - Tuesday, October 16, 2007 - Whoops! I meant..

<asp:Literal id="x" runat="server" Text="<%#Foo %>">

isn't really any different from

<%= Foo %>

except for more typing. They can both be considered alternative syntax for the same result.
Gravatar
Rob (not connery) - Tuesday, October 16, 2007 - That didn't work quite right...

was trying to
[quote]
These guys are usually the mock turtleneck-wearing guys who hang out by your desk trying to learn to code :). These guys know Visual Studio, but also know 'runat=server' and '
Gravatar
Rob (not connery) - Tuesday, October 16, 2007 - Sorry everyone... not going to try quoting it agian... classic line though!

just wanted to say that about 3 months ago I found my self on the code-behind side of this argument (against a PHPer)... started digging into monorail recently and find that every view I script is pulling me the other way.
Gravatar
DotNetKicks.com - Tuesday, October 16, 2007 - Crazy talk: Inline scripting and code-behind... You've been kicked (a good thing) - Trackback from DotNetKicks.com...
Gravatar
Gavin Joyce - Tuesday, October 16, 2007 - Great post. I was one of the many caught in the server control/viewstate headlights when asp.net first arrived. I always kept business logic out of the UI but the control/page events and databinding usually led to a mass of code split between the aspx page and code behind. Working with Rails for over a year has changed my opinion on inline scripting in the UI. Simple views are simply better. Roll on the ASP.NET MVC.
Gravatar
Some.Net(Guy) - Tuesday, October 16, 2007 - I was always taught to avoid inline coding at all costs when I was a "mock-turtleneck wearing guy," but since escaping the cube jungle and working for myself, I've recently started adding a bit of inline stuff and realized that, you know what, it's ok to have a little bit of inline here and there.
Gravatar
Michael - Tuesday, October 16, 2007 - As always, very insightful. When ASP.NET was introduced, I kind of shied away from the whole inline-code thing; and pretty much for all the reasons you stated. You've started a great conversation. This will have to be something I chew on for a while.
Gravatar
James Avery - Tuesday, October 16, 2007 - Like everyone else with ASP.NET I tried to minimize in-line scripting as much as possible, but when I started playing with RoR I realized how much I missed the simplicity and ease of just a little in-line scripting. It can be so much more readable and much more fun to write. The key is to avoid business logic in your scripting (like haacked said) and stick to just presentation logic. -James
Gravatar
16 Links Today (2007-10-16) - Tuesday, October 16, 2007 - [...] Crazy Talk: Inline Scripting and Code-Behind [...]
Gravatar
Denny Ferrassoli - Tuesday, October 16, 2007 - As I work more and more with JavaScript frameworks I've been leaving the Server Control behind as much as possible. I also really appreciate the fact that you can control your HTML output if you use inline script. That's why I can't wait for the MVC framework to come out.

Good post :)
Gravatar
Dave - Tuesday, October 16, 2007 - Unfortunately, I think the real problem we have is that "Mort" will never bother to worry about separation of concerns. He'll always either end up with too much presentation in code (too much code-behind) or with too much code in presentation (declaring inline variables, etc).
Gravatar
Joe Brinkman - Tuesday, October 16, 2007 - @Rob- Where to begin.... 1. Your code example is contrived - I would use a templated column and use html with ProductID bound directly directly in the markup. No code behind required. 2. You can read and grok what the page is doing in one glance. I have a table with x columns one is a link to a MyEditpage. 3. Set ViewState = false. No viewstate (Note: your ODS does not need the delete, insert, oldvalues or update attributes since these functions are not used in the inline example. Without these requirements, there is no need for viewstate - just bind on every view, just like you do with the inline code.) 4. You lose easy refactoring as your display needs change. It is much easier to get to spaghetti code from here, and once you start getting complicated, refactoring becomes non-trivial. In essence you have given up maintenance for a little bit of performance. Over the life of the project this may or not turn out to have been a wise move. Also, I would argue that in this case the handcoding method is more likely to lead to html errors and other logic issues which would be harder to track down - such as your mis-labeling columns in your table ;-)
Gravatar
Joe Brinkman - Tuesday, October 16, 2007 - Since these comments didn't like my html image tag, see my updated sample at http://www.theaccidentalgeek.com/Portals/0/gridexample.jpg
Gravatar
Darrell Mozingo - Tuesday, October 16, 2007 - @Joe: Even better, use the HyperLinkField column. Set its DataNavigateUrlFields to "ProductID" and its DataNavigateUrlFormatString to "ViewProduct.aspx?id={0}".
Gravatar
Anastasiosyal - Tuesday, October 16, 2007 - Im one of those guys who never liked web forms, no rant intended, but it just felt that the whole idea was 'and now you can create your web applications just like you do for your windows ones' which obviously was a step in the wrong direction with all that obscure serverside markup in the aspx file... Luckily enough for us the new MVC seems to be a corrective step in the right direction! This example is spot on, server side control and you feel like huh? What's the poet trying to say here...!? Whereas simple html some scrip and contollers... oh elegant and sexy! I dont like using postback heavy server controls and I do prefer to add script in the aspx file. In the end it comes down to how simple, elegant and readable the code is. There is a light beyond this tunnel since the MVC will hopefully enforce seperation of concerns, one would have to go out of his way to implement things in the wrong way! Oh, the future is bright!!!!!
Gravatar
Josh Stodola - Tuesday, October 16, 2007 - I think inline script blows. I feel that intermingling different languages is really confusing and, quite frankly, a true pain in the ass to maintain. Mixing Javascript, CSS, and HTML is enough; why would you want to throw yet another language into the mix? Plus, markup can be huge and the indentation gets ridiculous. Now you have to indent your inline code just to make it look like it fits in. Not to mention that in the end you are going to have ridiculous amounts of needless whitespace from your server-side scriptlets which will increase the size of the output.

No thanks. I think it's a very bad idea. Cleaner and more manageable? You must have been drunk when you posted this.

In your example, what would you do about an edit or delete button?

Best regards...
Gravatar
foobar - Tuesday, October 16, 2007 - This is a pretty contrived example. At least bother to use a Repeater to keep the examples somewhat similar.
Gravatar
Rob Conery - Tuesday, October 16, 2007 - @Joe: where to end? Yes my example was "contrived" - it was meant to show "the .NET WebForm Way" with the eventing model. Yes, I know I can use a template or a HyperLinkColumn.

# 2 - I don't agree. YOU might know what your GridView control is doing, but it's presence doesn't convey anything. Walking the "eventing path" leads devs to lean on grid events and the "OnItemDatabound" morass (see comment above) that really makes spaghetti yummy.

# 3 - so what's the point then? Why use the control?

# 4- I "Lose refactoring"? Nah - if I've done my layout right then I have a lot more flexibility with than the WebForm way.

I've not given up any maintenance - I've gained it. Please see my point where mention that scripting is layout only - any UI logic belongs in a centralized "helper".

"Also, I would argue that in this case the handcoding method is more likely to lead to html errors and other logic issues"

Can I get you some more KoolAid :):):)? If anything, HTML spun out by Render() methods (which is completely out of my control) is *questionable* - but that's a debatable point entirely. My overall point is that server controls abstract the HTML put out - I don't like that.

Finally - Server controls are code, and just another place that an error can crop up. The Load() event in a GridView, for example, is a complete nightmare to debug. Ever seen the empty GridView and wonder "where's my data???"
Gravatar
Mike Duncan - Tuesday, October 16, 2007 - I work on heavily SEO-ed sites so 100% control over all html rendered is important to us. I've struggled with the best way to make html tables for a while. I've tried in presenter code, in usercontrols as inline, and as repeater controls. I agree that inline looping is very close to the most desirable way to render tables (maybe having the datatable or generic list already waiting in the view, generated by a presenter). The problem that always seems to creep in is the modifiers you'll inevitably need in the table rows. If such and such a value is > this but
Gravatar
Rob Conery - Tuesday, October 16, 2007 - @Josh - Let me offer you some more languages to help your morning muffin go down: SQL, XML and LINQ. Dude if you have a problem "mingling languages" you're in the wrong industry. If you lift the page you're working on and peer at the code-behind, you just might see some more languages too!

Server markup is NOT HTML. It's declarative coding.

"Plus, markup can be huge and the indentation gets ridiculous" - if you do it poorly, sure. Do you validate the HTML that a GridView puts out? Care to comment on that?

"No thanks. I think it's a very bad idea. Cleaner and more manageable? You must have been drunk when you posted this."

Yah, I was having a beer while you were in the back room with your bong :). Needless whitespace? And the ViewState is what? And you're worried about your source view?

In terms of Buttons - i'm not sure what you're asking but I don't put them in grids; I use links. If I need to use a button I usually do HTML button. You remember how to do that right?

I should note that as I reread this comment - I'm having some fun with it :):):). See the smilies :). I do appreciate your thoughts...
Gravatar
Rob Conery - Tuesday, October 16, 2007 - @Mike: take a look at the Rails methodology. No logic belongs in your page and should be either part of the model (if it's a calc'd value) or part of a UI helper class. The idea is that "if's belong in code somewhere" and shouldn't be on the page.
Gravatar
Mike Duncan - Tuesday, October 16, 2007 - .. continued (dont put less than and greater than in your posts kids!) ..If such and such a value is greater than this but less than that, then wrap the current value in a span, or add a suffix to this word, etc, etc. Seems like we need something like xslt thats not so ... xslt-ish. These days I tend to put stringbuilders in my presenters which feel like they are close enough to the UI to me to be acceptable, although this is really not the case. Yeah I have to recompile, yeah its sucky. BTW, Subsonic rocks, makes .net feel very Railsy.
Gravatar
Yuriy - Tuesday, October 16, 2007 - I completely agree with you that ASPX without intellisense and without been able spot errors at compile time is very boring. However, I found that it is not easy to develop without component model supproted by ASP.NET. I don't use thrird party components and even avoid complex microsoft webcontrols, but for each application is is nice to create set of controls which represent your app semantics. These controls encapsulate presentation and if you use postabcks local behavior. (It is still possible to create controls and set their properties in incline-script code).

So, I hope that statically typed data binding is what we need. Even with MVC patern I like my input boxes to be able to do asyncpostbacks to support rich UI. I know that it is possible to develop completely client side AJAX controls talking to server (not to page itself), but is is as boring boring as data binding in ASP.NET.

I am trying to make ASP.NET handle generic classes like TypedDropDown. I got some results and it looks possible to get typed DataList control as well. (http://weblogs.asp.net/ysolodkyy/archive/2007/10/02/control-builders-amp-asp-net-generic-control-classes.aspx)
Gravatar
Rob Conery » More Crazy Talk: Inline Scripting and Slinging Text - Tuesday, October 16, 2007 - [...] Stodola left a good comment on my last post, and in part he asked: In your example, what would you do about an edit or delete [...]
Gravatar
Mark Brackett - Tuesday, October 16, 2007 - Add some inline editing, validation, personalized messages, etc. to those 2 pages and compare and contrast then....
Gravatar
Rob Conery - Tuesday, October 16, 2007 - @Mark - contrast what? Those things are just data right?
Gravatar
ASP.NET: Rethinking Inline Scripting « .NET Discussion - Tuesday, October 16, 2007 - [...] Rethinking Inline Scripting I came across an article called Crazy Talk: Inline Scripting and Code-Behind and it really made me rethink the way I program. The article discusses how the “taboo” [...]
Gravatar
amrlafi - Wednesday, October 17, 2007 - i like inline scripting over code-behind for various reasons : - code-behind did not provided the separation i was looking for, compare it to rails or any MVC approach ! - with inline scripting , as you mentioned, you can use less server controls (a lot resources friendly !) -for all smart stuff please stuck with ashx or asmx .asp.net folks really neglects them but they are too sexy when they are utilized :) -no more selfish developers to obfuscate code !! -almost 50% files reduction
Gravatar
D. Lambert - Wednesday, October 17, 2007 - Great example. The code in this example is readable and maintainable. As the "contrived example" starts to grow additional requirements, the inline code will grow, as well. At some point, doesn't it reach a density where it is no longer more readable than codebehind? I'm not sure that all developers will recognize this point, especially when they're right in the middle of it. As others have indicated, much of the "spaghetti code" of the past came from improper use of the tools available at the time. Rules like, "no inline code" don't exist because of top developers; they exist to keep average developers safe. (safer?)
Gravatar
Ben Scheirman - Wednesday, October 17, 2007 - I totally agree with what James Avery said, where I tried to go the full separation route and it ended up being more typing and generally more complicated. One thing that REALLY sucks when doing is that you cannot modify the control hierarchy at runtime. There are a ton of posts about this issue and the underlying problem makes total sense, but it's still painful. The one thing I disagree with you, Rob, is that ODS is good. I can't stand it, and it doesn't give us anything we couldn't do with less effort before. And don't get me started on SqlDataSource. I lived through cold fusion days and I don't wanna go back.
Gravatar
Josh Stodola - Wednesday, October 17, 2007 - >> Dude if you have a problem "mingling languages" you're in the wrong industry > Yah, I was having a beer while you were in the back room with your bong > Do you validate the HTML that a GridView puts out? > And you're worried about your source view? > In terms of Buttons - i'm not sure what you're asking > If I need to use a button I usually do HTML button. You remember how to do that right?
Gravatar
Josh Stodola - Wednesday, October 17, 2007 - Dude, your comment system is fucking worthless. There was a LOT more to my reply than that. See what inline scripting does?!

LOL
Gravatar
Rob Conery - Wednesday, October 17, 2007 - @Ben: LOL I absolutely abhor the ODS. Never... never ever. I just used it to show the "KoolAid Way". Josh I apologize for this - I use WordPress so it's sort of outta my hands. I'll see if I can resurrect the comment.
Gravatar
Josh Stodola - Wednesday, October 17, 2007 - Hehe, no big deal. Sorry for the unnecessary cursing, but I was angry at the time!
Gravatar
abc - Wednesday, October 17, 2007 - -- Rob Conery > When .NET was introduced this seemed like the way to go (cause they told us it was). This reminds me of Joel Spolsky's article, in which he coined the term "MSDN crowd." The MSDN crowd is Dino Esposito and his ilk who go gaga over every silliness that the boys of Redmond beget. When I started developing in AspNet I had to read hundreds upon hundreds of pages of documentation in order to understand how the beast worked. I read and re-read older issues of the MSDN magazine, in which the Dinos Espositos were waxing lyrical about how cool, elegant and great AspNet was. Oftimes, I wondered whether I was the only stupid kid on the block not to see any coolness or greatness. I wonder now what the MSDN crowd will be telling its gullible audience about the MVC Framework. I would love to see, in two or three years' time, the code produced by some enthusiasts rapturously swooning for joy over the new framework in your and Scott Guthrie's weblogs. Make no mistake, it will be spaghetti of the worst kind.
Gravatar
Rob Conery - Wednesday, October 17, 2007 - @abc - tough talk amigo! I can only assume since you didn't leave your name that you were joking :).
Gravatar
Jon H - Thursday, October 18, 2007 - As someone who has written thousands of lines of classic ASP, I will never go back to inline scripting. It becomes a maintenance nightmare, code behind separation has made my life much much much easier. Try comparing two real world applications, not simple grid view examples.
Gravatar
Rob Conery - Thursday, October 18, 2007 - @Jon H: I would argue the maintenance nightmare is your own fault. I don't see how putting code in the page behind is any worse then the one in front. Same stuff, different place right? I use inline scripting all over the SubSonic Forums - best thing I ever did. Tell ya what though, if you'd like to write a blog post and fill it with lots of code (as opposed to something simple to underscore your point) I'd be happy to read it. Let's see it! Back that statement yo!
Gravatar
o. s. - Thursday, October 18, 2007 - I really do believe that you're promoting bad coding pratice. Inline scripting only helps to break the barrier that should exist between business and presentation logic. Man what were you thinking when you posted this? I'm totally not convinced.
Gravatar
Rob Conery - Thursday, October 18, 2007 - @os: "It helps break the barrier" - Really? Code does that? For some reason I always thought it was the person in the chair that did that. What was I thinking? Well a lot of things really - and you can read them in my post. I'd like to know your reasoning, but since you're sparse with it, I'll just offer that you're wrong, I'm right :).
Gravatar
o. s. - Thursday, October 18, 2007 - @Rob

My reasoning is simple unrelated things shouldn't be put together in the source code.
A 'for each' loop in the middle of code whose job it is to present information to the user just doesn't make good sense and will be more difficult to maintain in the future.
Gravatar
Jon H - Thursday, October 18, 2007 - @Rob A properly designed aspx page should be extremely loosely coupled with the code behind, in my current project we have templated pages that are used over and over again with different code behinds. Maintenance is a breeze when a change needs to be made somewhere. Fill your aspx with inline code, and you have a page that can not be reused.
Gravatar
Rob Conery - Thursday, October 18, 2007 - @os: Come on homey - you can do better than that. Throwing "shoulds" at me without reason is basically saying "I do whatever I'm told and so SHOULD you". Nah - not for me. This statement: "A 'for each' loop in the middle of code whose job it is to present information to the user just doesn't make good sense and will be more difficult to maintain in the future." Is utter nonsense. PHP (the worlds most pervasive web framework) works precisely thus. So does Rails. So does ColdFusion. So does EVERY OTHER platform in the world friend - we're the only ones with this weird idea of UI code separation. So - explain to me how writing "foreach" on a scripted page (which is precisely what an ASPX is) is hard to maintain. And tell me why that's business logic as opposed to layout logic.
Gravatar
Rob Conery - Thursday, October 18, 2007 - @Jon H: OMFG are you serious? Did you just get your handbook of overused expressions? I'm surprised you didn't throw a "separation of concerns" in there :):):) (I'm having a little fun here - not being grumpy). So listen. You and OS here I think must work in the same dark corner of the MS Best Practices Cave. The term "Loosely Coupled" applies to logic tiers in your app - Data Access, Business Needs, UI Logic, etc. You don't want one to rely on the other. I think we agree on this, right? I think you might be one "those guys" who think it's better to put a Label on a page, and then bind the Text propery of that label to the code behind - right? Now, if yes, explain to me please how that BINDING "Loosely Couples" anything. Control is BOUND. And now you have two things to "maintain" - a control, and your code. More code != more maintainable. "Fill your aspx with inline code, and you have a page that can not be reused." - Nice statement. Let me know when you're done with the Soap Box cause I think O.S needs it...
Gravatar
o. s. - Thursday, October 18, 2007 - Just because everyone else does it, doesn't mean that you should follow suit. If everyone jumped off a bridge would you follow?
Why is this business logic and not layout logic? Everything about layout logic is meant to convey meaning about the placement and location of information and the 'foreach' (ok extra space last post :P ) doesn't convey info consistent with this.
I can see that you won't be convinced of any other reasoning so I'll just offer that these kind of coding pratices will come back to bite you later. :)
Gravatar
Rob Conery - Thursday, October 18, 2007 - @o.s. - sigh. I give up. If you offered any type of reasoning that involved something other than you "just stating it is so", I would be compelled. You're not. I give up.

Realize, friend, you are in a VAST minority with your opinion (including other platforms here). And your "back to bite you comment" applies to them, as well as me. And I find it hard to believe that you have all the answers. Or maybe you do and I've been arguing with God... who knows these days :).

Take a look outside the MS walls friends - it's a big world out there that is indeed round. They speak weird languages, use profanity, and do strange things like use "foreach" in a code page. And yet they look just like you and me!
Gravatar
Samuel Williams - Thursday, October 18, 2007 - I actually agree with you Rob. I don't think that the ASP.net model is good for a number of reasons: 1. High coupling between the view and the code-behind file. This is a problem because the resulting view depends highly on the use of code-behind controls, and makes me wonder, what is the point of having two files if they are so highly coupled? We cannot change the aspx without changing the code-behind file to reflect the change. I think this leads to messy code and unstructured business logic. I think having two files is a good idea, but the current situation is quite strange. 2. I agree that using inline scripting is the way to go, because it localizes the logic and functionality of the view. For example, it is easy to see that there is an html table with columns / rows / links, etc. But if we have an asp table control, we can't look in the view to understand what it is doing. This makes it slow to read that kind of code. 3. Why write code to produce HTML, when you can write simple and clean HTML just by itself? There is a good time to write code to produce HTML - when you repeat yourself a lot and want consistency and simplicity. Then, you should build some code to model the output you require. The consideration here is that you must determine that the model for your output is more complex than what can be represented using HTML - keep in mind that HTML is a very complete and For example, a candidate for this might be paragraph text that has certain words highlighted automatically. There is no way to express this implicitly using HTML, so we need to code an explicit addition to HTML to deal with it. Well anyway, that is just my idea. I don't really like ASP.net as a development framework.
Gravatar
Jeremy D. Miller -- The Shade Tree Developer - Saturday, October 20, 2007 - It's Smart to Challenge the ASP.NET Status Quo... One of my personal goals for our little ALT.NET movement is simply challenging the status quo for building...
Gravatar
Jim Losi - Sunday, October 21, 2007 - I read your comments and just had to stop and stare at your example for a minute and wonder why you had to do any of that. I don't know if it was because you tried to make the example look more inefficient as a result of some sort of subconscious effort to backup your pov or that sometimes as developers we simply forget about what the controls have to offer.. I know I do that from time to time and I'm sure I'm not the only one. At first I thought quietly.. a conditional based of off try parse might work better to reduce the code since TryParse returns a boolean value. Then as I started to look closer, I thought, why not the RowDataBound event.. then as I stopped to think and remove myself from your example, I realized that the hyperlink control already had this covered for you. No need to use ANY of that. Using a HyperlinkControl with the DataNavigateUrlFields prop DataNavigateUrlFormatString prop set to the appropriate fields would avoid/void your first example. So now we're just back to declarative code for the gridview. Then I read on to your inline example and the first thing that came to mind was "Wow.. flashback".. however, considering your "considerations" list with regards to your inline scripting example, I'd say I'd subscribe to points 1,3,4 and in a strictly black & white sense, point 5.... And you got me thinking. With my partial agreement on ponit 5, I considered my agreement/disagreement to be 50/50 and it pretty much put my perspective back into place. There are times when I hate ASP.NET and it's stupid controls and times when I love them; I hate not having full control over the HTML & the, sometimes, very large viewstates but there are times when DataKeys really fit the bill for me. Everything considered, I enjoyed your post because it brought me out of the pure asp.net control world and I will definitely consider inline scripting when applicable. Heh.. come to think of it, HTML controls weren't considered "dirty" for .. well.. since before ASP.NET..why are they considered dirty now? ;)
Gravatar
Joe Chung - Sunday, October 21, 2007 - Your inline code doesn't support sorting like your GridView/ObjectDataSource version does.

You could have made a hyperlink column do what you did with unnecessary code.

I respect your Subsonic work, but this blog post is just embarrassingly bad.
Gravatar
Rob Conery - Sunday, October 21, 2007 - @joe: LOL it doesnt "support sorting"? Well, that wasn't really part of the deal but it would take about 2 lines of code to enable. In terms of "embarrassingly bad" - well that's what I'm here for. I apologize for exposing you to different ideas... @joe, @jim - yes, I could have used a Hyperlink control.
Gravatar
Random0xff - Sunday, October 21, 2007 - Heh, I was one of those who challenged you in the subsonic forums. I was amazed to see code in the aspx like that. Í saw the video of the new ASP.NET MVC and now I understand better. But you must understand, I have seen classic ASP that would drive any sane man totally mad. I was reminded of that when I saw some code in the SubSonic starter kit that had an if/else to determine what HTML to display to a user. It still feels icky, but I understand better. I guess in the traditional webforms inline code feels out of place, but in an MVC framework view it would seem totally logical. Although the different html based on a user's role should be solved with two different views, to be determined by the controller, at least, that's how I now understand MVC. In the end Microsoft will actually create new webcontrols for use in the MVC framework, I wonder if they will give the same amount of functionality like GridView or TreeView? PS. Your gridview example is misleading, you can use databinding syntax to create the hyperlinks. A better example is to a gridview where you want to alter some row based on the data in it, the you'd _need_ the events.
Gravatar
Anatoly - Monday, October 22, 2007 - Hi. I want to see how you implement hiding/showing columns in code

above. And what if you build grid dynamically? It's a nightmare on

inline script. Once you ends using real gui component (like

GridView) you will end with endless routines and you will have to

write them over and over again on every page in your application.

Indeed in very rare simple cases your approach is worthy. Thanks
Gravatar
Charles - Monday, October 22, 2007 - I think anyone who prefers to use the codebehind method in ASP.NET

has not yet used in-line scripting in VS2008. A few things in my

recent experience has led me back to in-line scripting. First, I

had to make changes to an ASP.NET 1.1 web site that used

codebehinds and for which the source code had ben irrevocably lost.

Second, I have been developing web parts for MOSS and recently

switched to using Smart-Part and ascx files (coded in-line) in lieu

of deploying dlls. (If you don't know how painful it is to develop

and deploy web parts in compiled form to MOSS, count your

blessings.) Third, I have been asked to make changes to a very well

coded .asp/VBScript site who's judicious use of inline coding,

includes and VBScript classes make it the easiest application to

maintain that I've ever been handed, in any language/platform.
Gravatar
Rob Conery - Monday, October 22, 2007 - @Anatoly: you're woefully underscoring my point, amigo. So much of what we do on the server side (including sorting of tables) can be done in javascript. Libraries like jQuery make hiding/sorting/paging all of one line of code. I appreciate your thoughts, but it's this EXACT lack of knowledge of HTML/javascript that has led to inline scripting being spaghetti in the first place - spaghetti is as spaghetti does. In other words, the problem is not the tech, it's in the chair. Moreover, the Big Abstraction that is webforms has led us to this point: "If server controls can't do it, well it MUST be spaghetti". That's silly.
Gravatar
Steven - Friday, October 26, 2007 - Before reading, please forgive my scatter brain post here... I'm a good coder, but slow to organize my thoughts. Even slower at typing them. Took me 20 minutes to type this thing.


I can see both sides of the fense when it comes to the code behind/inline coding debate. The problem I have noticed is the lack of some server controls (ex. DataGrid....if I recall correctly) spitting out crappy HTML and that's simply unacceptable. Failing the W3C Validation is like getting punched in the face. So this is when inline coding becomes attractive... again. *looks back at ASP classic and grins* More control over the HTML is a good thing.

About two jobs ago, I was slapped on my wrists with a ruler each time I would write "spaghetti code" of any type, even if the performance was better or equal to it's server control counterpart. To this day, I still cringe when I write some type of inline code that could be seperated to the codebehind. Why do I feel I MUST use the code behind? Well, it's been a while since I've asked myself that question and I find that from an architectural point-of-view, it's a seperation of logic and UI for clean implementation. The UI homies work on the ASPX and the Logic homies work on the code behind. Makes for good organization, I suppose. It is all clean in my head at least.

The other side of my head screams, "Will using the code behind be most efficient in helping me get this project completed on time?". For most developers, there is a constant stress to deliver a pimpin' product before the ever present deadline. Will inline coding be faster and more efficient than coding with the code behind? Will this save my department money/time in maintenance for the poor soul that have to take over this project after I leave?

I'm not sure there is a right answer. I see both sides of the code behind/inline argument and I agree with both. It all boils down to what is most effective for you. As for me, I just use the code behind because that's how I'm most effective.

Though, I could just be completely retarded. Which is most likely the case. :)
Gravatar
Code + Markup, but why? - Sunday, October 28, 2007 - [...] read this post over at Rob Conery's site and I thought I would go ahead and post about it since I have actually [...]
Gravatar
Justin Etheredge - Sunday, October 28, 2007 - How perfect is this, I come across a post on Phil Haack's website about you going to work at Microsoft, which leads me to your blog. I read this article and it is exactly the same as a post I was working on, only much better and two weeks earlier. I am even embarrassed to post it here, but this is the link. By the way, good luck at MS! http://www.codethinked.com/post/2007/10/Code-2b-Markup2c-but-why.aspx
Gravatar
Justin Etheredge - Sunday, October 28, 2007 - @Steven I believe that the whole argument of code markup allowing the "UI homies" to work on the ASPX and the "Logic homies" to work on the code behind is somewhat of a fallacy. First off, unless the project is absolutely huge, I sincerely doubt that you are going to have separate UI guys and back-end guys. (Not saying that isn't a valid argument, just saying that it is not a concern for a lot of people.) But even when there is that separation I believe that the UI guys are going to be html guys, since we are dealing with the internet. Well, when you do the mark-up for asp.net you are dealing with anything but html. Not to mention the fact that the server tags you put in there can spit out any html and even if you *think* you know what html is going to be spit out it could be modified by a browser caps file, a control adapter, or even a control replacement in the web.config. This is anything but web programming, you really have no control at all over the html. If you did then things like the css control adapter wouldn't be necessary.
Gravatar
The Other Steve - Sunday, October 28, 2007 - I don't disagree with this. I just wanted to add something clarifying here, which I think confuses a lot of people.

My understanding, from the first I encountered discussions about MVC, is that the code-behind portion of ASP.NET is your controller. The .aspx page is your view. So that's where you get the confusion about separation.

That being said, if this is true, then I think this actually reinforces your point somewhat. Code which controls the view, makes perfect sense to be inline. So your example of the foreach loop building the table is a good one in that sense. Although I believe you can easily do the same thing with the DataRepeater, but then you still have inline code with the data eval constructs. So I think your way is clean in many ways.

However, I think code which controls the view, should be somewhere behind the scenes. So the call to data layer from your view grabbing the collection of objects is what is bothering people.

I've been using the MVP pattern described by Bill McCafferty over at http://www.codeproject.com/aspnet/ModelViewPresenter.asp in some of my recent work. This appears to me to be a good compromise between dealing with the oddities of the asp.net webform framework, and a desire to abstract out the view from the business logic. In the case of the MVP, you'd set a property on the aspx page with the presenter, and then your data interating code would take over.

Or I suppose you could load up a value in your Page_Load, and then reference that in your inline script. Either way.

Now, to the other point of view. By keeping the UI free of inline, and using user controls for these blocks of what you'd script out, you do make it easier for a web designer to mock up the page display without breaking things. Although in my projects, I never see this mythical web designer appear anywhere, so is that a useful argument?

I think this is good discussion. I'm eager to see where this new way of thinking takes us.
Gravatar
Avoid Spaghetti Execution with the Judicious use of Inline Scripting — blog.mattwynne.net - Tuesday, October 30, 2007 - [...] Conery has kicked up a right old hornet’s nest posting about the use of incline scripting in modern ASP.NET [...]
Gravatar
Tom Conery - Tuesday, November 06, 2007 - Rob,

Aloha! This is your cousin Tom in San Diego!!!! I attempted to send an email and am not sure if you received. Hope all is well in Hawaii. Have been spending quite a bit of time in Maui (Kihei). Hope fully this reaches you.

Regards,

Tom Conery
Gravatar
Richard P - Monday, November 12, 2007 - Your inline example doesn't HtmlEncode any of its data. It would break if a stray < or & got in the data. These are things we just didn't worry about in the old days. Inline code with HttpUtility.HtmlEncode all over the place doesn't save you any typing vs. a Label control, for instance. RE: sorting the table in JavaScript. That doesn't work with paged data, since JS can only sort the data on the page. I agree that there is still a use for inline scripting (heck, DataBinding expressions are all inline scripting of a slightly different flavor). Using inline scripting instead of code-behind for most things? I can't agree with that. When scope creeps, it's much easier to refactor the code-behind, in my experience. If you find yourself doing the same thing on page after page, you can refactor your code-behind into a control, for instance.
Gravatar
Jason Darby - Wednesday, November 14, 2007 - Let's not call it "in-line scripting." Let's call it "presentation logic." I want complete control over my HTML. Web Forms takes that control away from me. I want complete control over the HTML element ID names. The Web designers on my team want that too. They hate working with the long ID names that are generated by Web Forms. We are all for the example in this article!
Gravatar
Jarrod - Tuesday, November 27, 2007 - Loved the article, cleared up a lot of things for me. Also, I think I'll ask to have "HTML gunslinger" put on my business card - won't wear the turtle necks, but will continue to have around the developers desks.
Gravatar
David - Thursday, January 10, 2008 - Thanks muchly for an excellent post. I agree with separation of concerns but the Web Forms model does create a straight-jacket at times. I used this post to display details of an Order object and its child OrderLines collection in a precisely controlled layout with virtually zero-complexity. I have equivalent code doing the same thing with GridViews, FormViews etc, and I know which I'd rather maintain.
Gravatar
Rob Conery » Crazy Talk: Inline Scripting Revisited (Or, 2003 Bites Back) - Tuesday, February 05, 2008 - [...] ASP.NET MVC Framework and it’s support of Inline Scripting. As part of my community effort I decided to take this issue on a bit and try to remind people that inline scripting on it’s own isn’t spaghetti code - [...]
Gravatar
Steve - Tuesday, February 05, 2008 - Good stuff Rob. I see no difference in using c# code inline to handle presentation logic as I do using javascript to handle presentation logic. Key is, what is that logic doing? If it starts to become embedded business rules, then you've gone too far. If it's to loop through records for a display - then I think you're back in the UI realm. I wonder if people would complain as much about that code if it was a server control emitting the same html ?
Gravatar
Seth Petry-Johnson - Wednesday, February 06, 2008 - Too bad I missed this discussion the first time around! I've just recently begun dipping my toes in the icy cold water of Lake CodeInAspx, and so far I haven't found any piranhas :) For the most part I've been writing presentation-level methods [such as formatting some data in HTML] directly in the .aspx page. I prefer Repeaters over inline loops, but I'm not opposed to inline loops if they provide a cleaner, more readable, more _understandable_ solution than the code-behind route. I'm not advocating a wholesale return to inline business logic, but I do think that careful, thought-out use of inline scripting is a good tool to have in certain situations. I've spent enough hours debugging page lifecycle issues and dealing with obtuse .cs files that I'm in favor of ANYTHING that makes the programmer's intent easier to decipher, and easier to change when needed. Dogmatic avoidance of inline scripting is just as harmful as dogmatic avoidance of code-behind. Elegance lies somewhere in the middle.