<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>getiblog &#187; ui architecture</title>
	<atom:link href="http://blog.getify.com/tag/ui-architecture/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.getify.com</link>
	<description>javascript, performance, and ui musings</description>
	<lastBuildDate>Thu, 15 Dec 2011 17:37:04 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>You&#8217;ve got your orange thing, I&#8217;ve got my square</title>
		<link>http://blog.getify.com/orange-vs-square/</link>
		<comments>http://blog.getify.com/orange-vs-square/#comments</comments>
		<pubDate>Thu, 11 Nov 2010 22:21:37 +0000</pubDate>
		<dc:creator>getify</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Performance Optimization]]></category>
		<category><![CDATA[UI Architecture]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[middle-end]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[server-side]]></category>
		<category><![CDATA[templating]]></category>
		<category><![CDATA[ui architecture]]></category>

		<guid isPermaLink="false">http://blog.getify.com/?p=666</guid>
		<description><![CDATA[If you haven&#8217;t noticed yet, almost every one of my blog posts starts out as a twitter conversation. There must be a pattern there. So, today, I&#8217;m going to address the bigger issues around the question I first asked, which started off the conversation, seems inefficient: emulating a DOM (built up w/ server-side JS)&#8230;which then [...]]]></description>
			<content:encoded><![CDATA[<p>If you haven&#8217;t noticed yet, almost every one of my blog posts starts out as a <a href="http://twitter.com/#!/getify/status/2766997037252608">twitter</a> <a href="http://twitter.com/#!/getify/status/2768079054446592">conversation</a>. There must be a pattern there. <img src='http://getiblog.2static.it/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>So, today, I&#8217;m going to address the bigger issues around the question I <a href="http://twitter.com/#!/getify/status/2760342438412289">first asked</a>, which started off the conversation, </p>
<blockquote><p>
seems inefficient: emulating a DOM (built up w/ server-side JS)&#8230;which then has to serialize into a html string, transfer, then be rebuilt.
</p></blockquote>
<p>though it turns out I had to <a href="http://twitter.com/#!/getify/status/2772140415778816">rephrase it</a>, because I got <a href="http://twitter.com/#!/getify/status/2770918904434689">answers to a different question</a> than what I asked.</p>
<blockquote><p>
rephrase: i get why server-side js is awesome (code reuse, prog enhnc, etc). why a DOM approach instead of shared/reusable templating?
</p></blockquote>
<h3>Tale of Two Questions</h3>
<p>For the sake of sanity and clarity, let&#8217;s break down the conversation into the two fundamental questions, and address them separately:</p>
<ol>
<li>Why is server-side JavaScript helpful for front-end/UI tasks?</li>
<li>Why would you use the DOM approach to the UI in server-side JavaScript as opposed to a templating approach?</li>
</ol>
<h3>Server-side UI</h3>
<p>There&#8217;s some really exciting things you can do with the UI of your web application with JavaScript. This is probably not news to anyone who hasn&#8217;t had their head under a rock for the last 5-8 years.</p>
<p>But what role (if any) can server-side JavaScript have in the question of how to use JavaScript in the front-end of your application? Certainly that seems like an oxymoron to be doing JavaScript in your &#8220;back-end&#8221; primarily for the benefit and use of your &#8220;front-end&#8221;.</p>
<p>In fact, this is <em>exactly</em> why I&#8217;ve been banging the loudest drums I can find to try to define the <a href="http://middleend.com">&#8220;middle-end&#8221;</a> (that is, what sits in between the front-end and back-end&#8230; the middle-end!) of the web application stack. </p>
<p>Specifically, there are a number of UI-related tasks which frequently occur in both places &#8212; the browser and the server. For instance: presentation &#8220;construction&#8221;, data/form validation (or data binding), etc. These tasks, along with others, I have defined as the &#8220;middle-end&#8221;.</p>
<p>Moreover, concepts such as &#8220;progressive enhancement&#8221; are heavily related &#8212; that is, the idea of progressively enhancing the presentation layer capabilities depending on the capabilities of the client making the request.</p>
<p>Where server-side JavaScript offers some really exciting answers is:</p>
<ol>
<li><strong>Code Reuse</strong>: If I can write my data validation code, or my UI construction code, etc, <em>once</em>, <strong>in JavaScript</strong>, and then reuse that code in both the browser and the server, I&#8217;ve significantly improved the maintainability of my application by achieving <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a> (don&#8217;t repeat yourself).</li>
<li><strong>Progressive Enhancement</strong>: If I can take advantage of JavaScript&#8217;s ability to build out my page&#8217;s UI dynamically, I can achieve some really awesome things in the browser. But what about browsers which don&#8217;t have JavaScript (enabled)? The typical approach has been to serve a more basic version of the content to such less-capable browsers.
<p>But what if I could get most of the awesome benefits of JavaScript-powered presentation and not be affected by the browser&#8217;s inability to do JavaScript? What if I could run all my awesome JavaScript to build up my page (or even to dynamically alter it) on the server, and just send the HTML result of such operations over to a less-capable browser? To the user of such a browser, they might see things updating slower and a little less gracefully (with full page-refreshes), but they&#8217;d get most of the benefits of a dynamically capable page experience without having any JavaScript at all. </p>
<p>This could be a <strong>huge</strong> win for progressive-enhancement advocates, because it significantly reduces the amount of work that a site must do to provide some sort of alternate content experience for JavaScript-less browser users.</li>
</ol>
<p>These are not the only interesting ways that server-side JavaScript could be used to really revolutionize the web application process, but they should be more than enough to answer the question: &#8220;Why is server-side JavaScript helpful for front-end/UI tasks?&#8221;</p>
<h3>To DOM or not to DOM</h3>
<p>The meatier question in play here is, if we agree that server-side JavaScript should be used to improve the web application stack, should we choose a DOM-based approach to building out the UI on the server, or should we use a string-templated approach?</p>
<p>I&#8217;ll cut to the chase. <strong>The short answer is&#8230; BOTH!</strong></p>
<p>But the nuances of that assertion are what we&#8217;ll now focus on for the rest of this post.</p>
<h3>Oranges &#038; Squares</h3>
<p>Let&#8217;s first define more specifically what we mean by each distinct approach:</p>
<ol>
<li><strong>DOM approach</strong>: By this, I mean that you build up your page by explicitly creating each element as a node in a DOM tree. For instance, if I want to add this &lt;ol>&lt;/ol> ordered-list to my page, I first create an &#8220;ol&#8221; node, then I create an &#8220;li&#8221; node, then I append some text to the &#8220;li&#8221; node (as a &#8220;text&#8221; node of course), then I add the &#8220;li&#8221; node to the &#8220;ol&#8221; node, etc. Once my &#8220;ol&#8221; node is ready, I then append my &#8220;ol&#8221; node as a child element of some part of my page, like the current section I&#8217;m in.
<p>Such an approach might look like this (using jQuery):</p>
<pre class="code">
var $ol = $("&lt;ol>&lt;/ol>");
var $li = $("&lt;li>&lt;/li>");
$li.text("Some text");
$ol.append($li);
$("body").append($ol);
</pre>
<p>With this code, our JavaScript executes and programmatically builds up our DOM elements, eventually adding our &#8220;ol&#8221; element to the end of the &#8220;body&#8221; element.
</li>
<li><strong>Template approach</strong>: By contrast, here I mean that to build up the &#8220;ol&#8221; list as described above, you instead create a string like &#8220;&lt;ol>&#8221;, followed by a &#8220;&lt;li>&#8221;, then some text, then &#8220;&lt;/li>&#8221;, etc. Once the entire string of markup is done, then you insert that entire string into the page (or part of the page), either as the full HTML or as the <em>.innerHTML</em> of some element.
<p>Of course, I&#8217;m not suggesting that you literally have to manually add strings together with variables and such. That&#8217;s why we have template engines that do that for us. So, instead, you have a template like this:</p>
<pre class="code">
&lt;ol>
   &lt;li>{some_text}&lt;/li>
&lt;/ol>
</pre>
<p>With this &#8220;code&#8221;, our templating engine grabs the <code>{some_text}</code> part and replaces it with the value of that variable, and returns us the full constructed string, so we don&#8217;t have to mess with all the string operation details.</li>
</ol>
<h3>Zoom In</h3>
<p>So, let&#8217;s examine the differences between these approaches.</p>
<p>The first most obvious difference is what the &#8220;code&#8221; looks like that generates something visible in our presentation layer. In the DOM approach, large chunks (if not all) of your presentation layer is written in JavaScript <em>code</em>, usually tucked in with all the other front-end JavaScript. In the templating approach, almost all of your presentation layer is in HTML markup (as a string), usually in separate template files.</p>
<p>The result of building your UI in the DOM approach is an actual DOM tree (a physical nested object heirarchy in memory). The result of building your UI in the template approach is just a string of HTML markup.</p>
<p>Let&#8217;s be clear about something: <strong>a DOM is required to render something the user can see</strong> in the browser. So, the string of HTML markup that you get from the templating approach must of course eventually get parsed into a DOM tree.</p>
<p>That presents an obvious question: if a DOM is eventually required to actually <em>show</em> the presentation layer, isn&#8217;t it more efficient to just start out with (and stay in) the DOM tree, rather than going with string manipulation as a first stage of the process?</p>
<p>This is a fine and fair question. I hope I can quickly distill a few thoughts to suggest why I&#8217;m not so sure that the <em>obvious</em> is entirely correct &#8212; there&#8217;s more here than meets the eye.</p>
<h3>Designers</h3>
<p>Firstly, I&#8217;d suggest that there&#8217;s a pretty strong precedent for building HTML pages in&#8230; HTML. Designers, IDEs, and most web developers have learned and in many cases mastered the process of writing HTML markup. To my knowledge, almost none of the web development IDEs and typical processes are centered around an &#8220;(DOM)object-oriented&#8221; building of pages &#8212; in other words, I&#8217;ve never personally seen an IDE where when I look at source-view of a page, I&#8217;m messing around in a nested tree structure and adding and removing nodes.</p>
<p>Moreover, the very concept of a string of HTML markup actually conceptually representing a hierarchy of parent and child nodes is a very programmer-centric view. It&#8217;s like the difference between saying &#8220;The Quick Brown Fox&#8221; is a sentence phrase versus saying that, as a programmer, that&#8217;s actually an array of individual characters. Both are true, but one view is more semantic and the other is more programmatic.</p>
<p>So, stylistically, you can make a strong case (although it is ultimately preference-driven) that building out HTML pages is more natural and well-established as HTML markup as opposed to JavaScript code. From purely a role-separation standpoint, it&#8217;s perhaps more natural for UI designers (and the markup/CSS role) to be able to work in simple HTML markup than they will in code (whether that be JavaScript code, or some other back-end language code like PHP, Java, .NET, etc).</p>
<p>Just because we layer on a simple templating engine on top of the HTML markup to represent the concept of dropping in a dynamic data value in a certain location, doesn&#8217;t mean we&#8217;ve changed the paradigm from working with HTML markup to working with DOM nodes. Of course, some &#8220;templating engines&#8221; are far more complex, including all kinds of &#8220;programming-like&#8221; stuff, like conditionals, loops, function calls, arithmetic, boolean logic, etc. The more of that junk you cram into the &#8220;templating language&#8221; of your choice, the more like programming your presentation layer construction becomes.</p>
<p>As should probably be obvious, my strong preference is at the far simple end of the templating spectrum, where a bare minimum of anything that looks like &#8220;programming&#8221; is going on inside my HTML markup. I think that&#8217;s backed up by lots of precedence in &#8220;separation of concerns&#8221;, and I believe a lot of people agree. But there are others who prefer to write <em>code</em> to build up their presentation layer. To each his own, on that, I guess.</p>
<h3>Down To The Wire</h3>
<p>The other major difference, when we factor in such tasks as presentation layer building occurring on the server, is how the stuff that gets sent over the wire is prepared for the trip from the server to the browser.</p>
<p>In either the DOM or template approach, if the browser doesn&#8217;t have JavaScript enabled, the entire process of building the presentation layer occurs on the server, and what gets sent over the wire is always and only a string of HTML markup. The exact same page built with the DOM or template approach will end up being exactly identical when it squeezes down to fit through the pipe from server to browser &#8212; a string. </p>
<p>If we accept that in that base case, what transfers over the wire must be a string, then the question above of what&#8217;s more efficient (DOM or string) gets flipped. If the in-memory representation of the DOM (on the server) must first be down-converted to a string to be sent over the wire, <strong>this will tend to be less efficient than if the presentation layer is already (and only) just a string, ready to send.</strong></p>
<p>Now, what about the case where JavaScript <em>is</em> available on the browser? Assuming then that we&#8217;re in the part of a task where we want to off-load our presentation construction to the server, what gets sent over the wire is still going to be pretty much equivalent (though not the same). For the DOM approach, we&#8217;re going to send JavaScript, probably in the form of .js files, and in the template approach, we&#8217;re going to send HTML templates (strings), probably in the form of template text files. In each case, the files will be normatively cacheable to about the same extent.</p>
<h3>Run Time</h3>
<p>Both approaches are going to need JavaScript though, not just the DOM approach. The template approach is going to need a &#8220;template engine&#8221; that can do the same tasks that it did in the on-server scenario &#8212; do string operations and combine the string content with dynamic data. The DOM approach is going to need JavaScript logic to create, insert, append, and modify the in-memory DOM tree.</p>
<p>I don&#8217;t have conclusive statistics to suggest that either of those two JavaScript code logic paths are going to be substantially faster or more efficient than the other. String operations have, especially in recent JavaScript engines, become exceedingly optimized and fast (compared to really bad string performance in previous generations). Moreover, an intelligent template engine is going to &#8220;cache&#8221; the compilation of a template (that is, all the string parsing) into repeatedly-executable code, so the costly regular-expression-like parsing of the template string approach is going to be drastically reduced, considering the whole life time of the page view.</p>
<p>But let&#8217;s examine what happens at the moment when the presentation layer is about to cross the bridge and actually be added to the live DOM of the page. In other words, let&#8217;s compare whether it&#8217;s more efficient to inject a single ready string of markup via .innerHTML or to append a sub-tree of nodes to the main DOM tree. Fortunately, a <a href="http://jsperf.com">jsPerf</a> test exists to help answer this question: <a href="http://jsperf.com/dom-vs-innerhtml/10">DOM vs. innerHTML</a>.</p>
<p>I ran this test a few times in a few different browsers, and got conflicting results. In Webkit (Chrome/Safari), I got that the DOM insert was quicker (30-50% so) than the .innerHTML insert. But in FF (and to some extent, IE), I got the opposite. Opera was 40% faster at the .innerHTML than at the DOM insert. So, those results are mixed to say the least. I do however think it&#8217;s fair to say that as we would go back in time to older generations of browsers, the .innerHTML insert would tend to be a little faster, since most of the attention and focus in recent optimizations of the DOM has been in the DOM append operations. This is a conjecture at best on my part, but I think it&#8217;s not terribly inaccurate.</p>
<h3>Ideal vs. Realistic</h3>
<p>And let&#8217;s look closer at what&#8217;s going on in this test. The DOM insertion test case uses a <a href="https://developer.mozilla.org/En/DOM/DocumentFragment">DocumentFragment</a>, basically a temporary non-rendered DOM sub-tree, to append the children nodes to. Why go to this effort? Because it&#8217;s common knowledge that the absolute slowest part of anything you can do in JavaScript is the actual DOM manipulation against the live DOM of the page.</p>
<p>The reasons for this are varied, but include even things like how DOM manipulations require updating of internal live nodeList collections, force the rendering engine to do reflow and repaint, etc. So, if we can do all our DOM manipulation in a disconnected sub-tree without such side effects, we&#8217;ll drastically reduce the cost of DOM insertion. This is a well known and cited optimization technique that has very tangible effects. If that same jsPerf test were run without the use of DocumentFragment and were just inserting the children directly into the live DOM one at a time, <strong>the DOM insertion test case would have been hundreds or thousands of times slower across all browsers.</strong></p>
<p>So, are the DOM approach and template approach tied or inconclusive in terms of run-time performance? Perhaps. But I&#8217;d say maybe not. The test above represents the absolute best-case optimization, where you have everything you need for the DOM ready in a fragment, and can do it in one insert. In the real world complexity, you may have cases where you need to do 2, 3 or even 10 inserts all around a page. Because the overhead of the live DOM insert is, in general, much higher, the more of them you do, the quicker that negative performance will add up, and will be slower than the .innerHTML inserts.</p>
<h3>DOM > string</h3>
<p>There are a few cases where some valid arguments can be made that modifying the DOM dynamically is easier or better than dealing with HTML strings. </p>
<p>For one, whenever we&#8217;re dealing with event handlers (which get bound directly to DOM nodes), if you start re-assigning the innerHTML of nodes (or the entire page), you&#8217;re likely to screw up your event handlers. This is a common and costly mistake. It can of course be mitigated by the established best practices of using event bubbling/delegation, where you have event handlers bound only to top level DOM elements (like the body, for instance), which listen for bubbled-up events from any child elements &#8212; when you do it this way, you can freely re-create your elements using either DOM manipulation or innerHTML, and not mess up the event handling.</p>
<p>However, let&#8217;s keep in context what this post was about. If we&#8217;re talking about doing DOM building of a page on the server, we don&#8217;t have browser event handlers in place, so this problem is moot. </p>
<p>Another argument for the DOM approach is the ability to use CSS Selector Engine searching to find elements in the DOM tree. There&#8217;s no doubt that Selector Engines are extremely powerful, and using them to traverse through a DOM is equally so. But, when dealing with server-side DOM building, it&#8217;s less likely that you&#8217;re going to be layering on modifications to your DOM where you need to search the entire DOM repeatedly. For instance, you may be using the DOM approach, and you may &#8220;attach&#8221; a widget to the server DOM representation, where it creates a new set of DOM nodes to represent itself. But it probably won&#8217;t need significant CSS Selector Engine functionality to parse through the entire DOM when doing so &#8212; it&#8217;ll probably just operate locally in one area of the DOM.</p>
<p>And even if you did need to be able to push in different content into different places of your &#8220;page&#8221; (attaching different widgets), the regular expression&#8217;s power over string searching should be equally capable for most tasks. Your template engine can use a layered approach, where you have sub-template place holders for each widget, and you can tell the template-engine to build out each sub-template separately.</p>
<p>In short, there are cases where we may be more <em>used</em> to tasks (which we normally do in the browser) by using the DOM approach. But there&#8217;s not much if anything that can only be done with DOM and is impossible or impractical with string templating. It may take a slightly different mental shift to do so, but I believe templating can be every bit as useful (and perhaps even more so) as the DOM approach.</p>
<h3>Oranges AND Squares</h3>
<p>Let me wrap up this post with some final thoughts.</p>
<p>Firstly, as you&#8217;ve seen, there&#8217;s some awesome benefits to using server-side JavaScript to build your presentation layer UI. But more importantly, there&#8217;s more than one way to use server-side JavaScript to build it. You can use the DOM, you can use string templating, and you can do both in the same page as you see fit.</p>
<p>I&#8217;d just encourage you to realize that the DOM is merely a concept that the browser forced upon UI developers &#8212; it&#8217;s not actually the most natural way we deal with HTML for the presentation layer. The DOM API in the browser has some really ugly and non-performant warts, and yet some people are going to great efforts to emulate the DOM on the server. I wonder why we&#8217;re trying to shoe-horn the DOM into the server to accomplish our tasks, rather than using a string-templating approach that can work pretty naturally and capably in both places <strong>without any extra emulation layer</strong>?</p>
<p>But even if you&#8217;re unconvinced that the DOM is sort of an abnormal approach for the server-side presentation layer building, at least accept that both the DOM and templating approaches will serve you well. Pick which one (or both) is best for each task, and for each part of your development team. </p>
<p><strong>Don&#8217;t just assume that because YUI or jQuery are DOM-centric, that this is the only way to achieve server-side JavaScript presentation layer logic.</strong> A good, intelligent templating engine will give you all the same tools, and may just be a more natural and efficient fit in the long run.</p>
<div><a class="addthis_button" href="//addthis.com/bookmark.php?v=250" addthis:url='http://blog.getify.com/orange-vs-square/' addthis:title='You&#8217;ve got your orange thing, I&#8217;ve got my square '><img src="//cache.addthis.com/cachefly/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a></div>]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/orange-vs-square/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JSConf 2010 &#8211; getify on middle-end/ui architecture</title>
		<link>http://blog.getify.com/jsconf-2010-getify-on-middle-endui-architecture/</link>
		<comments>http://blog.getify.com/jsconf-2010-getify-on-middle-endui-architecture/#comments</comments>
		<pubDate>Tue, 03 Aug 2010 18:25:10 +0000</pubDate>
		<dc:creator>getify</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[UI Architecture]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[middle-end]]></category>
		<category><![CDATA[ui architecture]]></category>

		<guid isPermaLink="false">http://blog.getify.com/?p=516</guid>
		<description><![CDATA[JSConf 2010, Track B, "Dude, Where's My UI Architecture?"]]></description>
			<content:encoded><![CDATA[<p><embed src="http://blip.tv/play/g_MngemSLgI%2Em4v" type="application/x-shockwave-flash" width="480" height="346" allowscriptaccess="always" allowfullscreen="true"></embed></p>
<div><a class="addthis_button" href="//addthis.com/bookmark.php?v=250" addthis:url='http://blog.getify.com/jsconf-2010-getify-on-middle-endui-architecture/' addthis:title='JSConf 2010 &#8211; getify on middle-end/ui architecture '><img src="//cache.addthis.com/cachefly/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a></div>]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/jsconf-2010-getify-on-middle-endui-architecture/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grab UI by the Handlebar</title>
		<link>http://blog.getify.com/grab-ui-by-the-handlebar/</link>
		<comments>http://blog.getify.com/grab-ui-by-the-handlebar/#comments</comments>
		<pubDate>Sun, 21 Feb 2010 21:53:03 +0000</pubDate>
		<dc:creator>getify</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[UI Architecture]]></category>
		<category><![CDATA[handlebar]]></category>
		<category><![CDATA[handlebarjs]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[templating]]></category>
		<category><![CDATA[ui architecture]]></category>

		<guid isPermaLink="false">http://blog.getify.com/?p=234</guid>
		<description><![CDATA[A couple weeks back, I talked about HAML and why I&#8217;m not a fan of its approach. I promised in that article that I would be following up with some discussion of how I think UI templating should work. I intended to post earlier than this, but then I dove into a fun new coding [...]]]></description>
			<content:encoded><![CDATA[<p>A couple weeks back, I talked about <a href="http://blog.getify.com/2010/02/why-i-dont-like-haml/">HAML and why I&#8217;m not a fan</a> of its approach. I promised in that article that I would be following up with some discussion of how I think UI templating <em>should</em> work. I intended to post earlier than this, but then I dove into a fun new coding project (which I will write about here soon), and I&#8217;m just now resurfacing for air.</p>
<p><strong>Disclaimer</strong>: The criticisms I have of various web application frameworks and platforms are not <em>entirely</em> universal. There <strong>are</strong> some solutions out there which have vastly improved their approaches. For instance, I&#8217;ve borrowed some good parts from Django, <a href="http://github.com/janl/mustache.js">Mustache.JS</a>, even (whisper) .NET MVC. The problem is, the bad stuff is so overwhelmingly prevalent in the development community, it chokes out the life of those who really are trying to make it better. Add my voice to <em>that</em> list, and a +1 for all the others who are on that same page.</p>
<p>This will not be a simple quick post. There&#8217;s so much I need to write, and it just can&#8217;t all fit into a few paragraphs. Please bear with me as I expound on this topic.</p>
<h2>Handlebar?</h2>
<p>Before I go into further explanation, go check out <a href="http://github.com/getify/HandlebarJS">HandlebarJS Template Engine</a>, my entry into the arena of how to construct web UI. It&#8217;s important to note, this is <strong>not</strong> some &#8220;Yet-Another-&#8221;  all-in-one framework that has sexy themeable widgets, a CMS, or auto-generated admin interfaces. All you will find there is a basic, simple Templating Engine, that takes JSON data as input, processes and compiles text-based templates (that you create and control 100%) into &#8220;executables&#8221;, and pumps the JSON data into the compiled templates to return a &#8220;View&#8221;.</p>
<p>There&#8217;s much more planned for HandlebarJS, including tools for build-processes, filters, compression, UI optimization, etc. They will come in the form of loosely coupled &#8220;plugins&#8221; that are compatible with HandlebarJS&#8217; &#8220;view&#8221; of the world.</p>
<p>HandlebarJS is really quite the opposite of most UI frameworks: it&#8217;s a stripped down, deconstructed, anti-framework tool for what is now being called the &#8220;middle end&#8221; &#8212; the stuff that sits between the front-end and the back-end, and negotiates communication, View construction (templating), URL routing, data validation, and other fun things. </p>
<p>What HandlebarJS is <strong>not</strong> is <em>any</em> kind of RIA framework that attempts to handle the behavioral side (JavaScript) of rich UI. HandlebarJS is only concerned with as quickly and efficiently as possible generating the markup for the UI.</p>
<p>HandlebarJS is intended to be one of several independent components for re-thinking the middle-end UI architecture of web applications. Those other components deserve their own full projects and explanations/write-ups, so you&#8217;ll just have to keep an eye out here over the coming weeks for those.</p>
<h2>Why should I care?</h2>
<p>You may ask yourself at this point: &#8220;I have XYZ framework or platform (.NET, Java/Swing, RoR, Django, etc) already, and it does all that stuff for me. Why do I need something else?&#8221; Well, that&#8217;s a great and valid question, one that deserves a lot more discussion than can ever fit into one blog post. I do have a very specific set of answers to that question, and I will be unveiling it little by little through blog posts (including this one), separate dedicated websites, and even an upcoming planned book.</p>
<p>For now, I&#8217;m going to ask you the reader to take my word just a little bit &#8212; that&#8217;s there strong reasoning behind what I&#8217;m trying to do &#8212; and let me develop and explain it bit by bit. This post will present some of the high level motivations and discuss specifically HandlebarJS for templating &#8212;  my goal for now is that you&#8217;ll come away more knowledgeable about <em>just <strong>an</strong> alternative</em> to how your web application currently approaches its Views. I&#8217;m not <em>yet</em> trying to convince you that you need an entirely different application architecture &#8212; we&#8217;ll get there slowly, and it won&#8217;t be as scary as it may seem.</p>
<h2>What am I trying to solve?</h2>
<p>I don&#8217;t want to re-write here the entire article and underlying arguments I had against the HAML approach. But, I do encourage you <a href="http://blog.getify.com/2010/02/why-i-dont-like-haml/">to read it</a> to understand better where I&#8217;m coming from.</p>
<p>However, here are the primary thoughts that were motivating factors for creating HandlebarJS:</p>
<ol>
<li><strong>DRY and Portability</strong>: For decades, the development community has operated (to varying degrees of authenticity and success) under the principle of not repeating yourself, meaning as much as possible, don&#8217;t have two different sets of code that do the same thing. The advent of functions/sub-routines laid the ground work years ago, upon which Object-Oriented programming expounded to give us even better patterns for write once, use many.
<p>The problem is, the explosion of the web application paradigm has thrown several wrenches into the mix. What fundamentally used to be a single monolithic application, or even a straightforward server-client application, is now a highly complex, distributed, cloud-integrated, web connected, desktop and mobile consumed, rich, thin-and-thick application conglomeration that challenges with orders of magnitude more complexity than our older patterns are capable of handling. It&#8217;s almost like we went from n-tier to n^2-tier architecture in a relatively short period of time.</p>
<p>Moreover, the paradigm of the presentation layer residing in a browser has both extended <em>and</em> limited the evolution of such applications. For several years, even after the invention of Ajax (which revolutionized the page-refresh), web developers have struggled with wanting to do more with Rich Interfaces than the browser (or even internet connection or host computer) was capable of handling. The latest generation of browsers, web technology standards, and computing equipment has finally broken down many of those barriers.</p>
<p>But just as we finally got to the point where the desktop web browser could be an effective tier in the overall application (not just a thinly veiled client), now we have an intense push to extend all our web application presences into a new frontier of &#8220;connected&#8221; devices (mobile, smart phone, netbooks, etc), many of which are (in some ways) throw backs to the performance (CPU, connection speed, etc) we could rely on with desktop browsers 5 and 8 years ago. </p>
<p>Even as mobile Safari pushes to implement the latest and greatest HTML5/CSS3 standards, the reality is that mobile web apps are still handcuffed by limited processor capacity, severely limited browser caches, and unreliable (at best) connectivity.</p>
<h3>So what does all this have to do with DRY and portability?</h3>
<p>I believe we are at an inflection point in the web UI evolution where we must start to think about things differently if we have any hope of keeping up with the exponentially complicating trends of consumer technology. We&#8217;re starting to see the fundamental inadequacies (and the pain it brings) of established solutions, in their inability to efficiently handle the rapidly expanding array of consumers of UI presentation.</p>
<p>These all-in-one frameworks are so attractive to development teams because they fully abstract away all of the messy details of how markup and data are combined to be the delivered UI product. But with that ease-of-use comes a price &#8212; lack of flexibility to control and optimize such UI delivery on the fly depending on who is consuming it. A fancy .NET list widget may rock for UI delivered in IE8 on a desktop, but is it up to the task of usable and functional behavior/display in a mobile Opera browser on a screen 1/16 the size of a laptop screen and with 1/10 the memory and CPU? The sad answer is often: absolutely not.</p>
<p>And no, it&#8217;s not enough to just have a different stylesheet for mobile browsers and expect that CSS will save the usability of your app. Mobile (narrow-screen) is an entirely different paradigm in almost all respects to desktop computing. To effectively leverage both platforms simultaneously, <strong>AND</strong> with the same (unrepeated) code bases, we&#8217;re gonna have to get a lot more creative.</p>
<h3>&#8220;And now, for something completely different&#8221;</h3>
<p>We need an approach to UI that is powerful yet compact, that is portable (meaning it can run in both a server environment and in a variety of browser host environments), and that is flexible enough to be extended/composed/dissected/etc as necessary for the different devices consuming the UI. This isn&#8217;t just an incremental improvement on existing systems, it&#8217;s an entirely new new kind of approach.</p>
<p>Of course, if you <em>prefer</em> to write code over and over again, and maintain different application branches for different presentation consumers, then you&#8217;ll probably totally disagree with me here &#8212; you&#8217;d probably rather just stay the course. But I think the future is more re-use and convergence, not less. And I make no apologies for the fact that this is my <strong>fundamental bias</strong> for everything I&#8217;m trying to do here. I <em>do not</em> like at all to <em>Repeat Myself</em>, and I&#8217;m going to do everything I can to keep that out of my development practices.</p>
<p>And I&#8217;m just crazy enough to believe in the idealism that it IS possible to achieve this utopia. We&#8217;re just gonna have to be brave enough to question everything we&#8217;re currently doing. No big deal, right?
</li>
<li><strong>Do front-end type work in&#8230;&lt;gasp>&#8230;ONLY front-end technologies</strong>: I feel like I&#8217;m probably admitting frequently on this blog to not only being strongly opinionated but also a little bit crazy. But that&#8217;s ok with me. I can tell you we are not gonna ever solve any real problems by thinking the same way we always do. And I like that I&#8217;m a fundamentalist &#8212; that I believe less is more.
<p>I think we could use a lot more of that mindset in the development community. You wouldn&#8217;t get in a jet-liner to travel up to the corner store &#8212; so why do we feel that these immensely complex frameworks and platforms are the right approach to web applications?</p>
<blockquote><p>
Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.  &#8212; Antoine de Saint-Exupery
</p></blockquote>
<p>Let&#8217;s face it: we all (at one time or another) entertain dreams that <em>our</em> web application is going to need to scale to hundreds of millions of concurrent requests, and our development team is going to balloon to hundreds of distributed development groups, and we must <em>plan</em> for that now by using an enterprise-ready <em>Solution</em>.</p>
<p>Yet, when you look at the world&#8217;s biggest web applications &#8212; the Googles, the Yahoos, the Facebooks, and the Twitters of the world &#8212; you actually don&#8217;t see them using such non-sense to drive their applications. In fact, you often see fundamentalism blatantly plastered across their approach. Why? Because as things scale, what&#8217;s not needed is <strong>more</strong> machinery to manage it, but <strong>less</strong> to abstract away and play middle-man in the transformation of a request into a response.</p>
<h3>This post is about UI, right?</h3>
<p>Nowhere is this more true than in the UI layer (the middle-end). It&#8217;s been recently suggested by <a href="http://stevesouders.com">Steve Souders</a> of Yahoo and Google fame that actually most of the performance bottle necks (of small and large applications alike) is the UI layer.</p>
<p>My thesis: the fewer layers of abstraction sit on top of the presentation layer, the more efficient the application will operate (in both low and heavy traffic situations). My corollary: This fundamentalist approach to UI will <em>also</em> lead to better separation of skillsets &#8212; a front-end engineer can completely control the UI of an application using <strong>only</strong> front-end technologies like HTML, JavaScript, and CSS, which they are likely best at. </p>
<p>This means that when they want to streamline the way their UI is constructed and delivered to address a page-load efficiency issue on their site (like JS/CSS concatenation for instance), they can get directly and immediately to the problem, <em>in the front/middle-end layer</em> (instead of wading through who knows how much back-end cruft that they may or may not be fully capable of navigating or changing). They can also use the technologies they are likely most familiar with (their core skillset) to solve the issues.</p>
<p>This may seem like a trivial distinction. But I believe it&#8217;s a critical and overlooked factor in developer efficiency: staying within one&#8217;s core skillset &#8212; the sweet spot &#8212; as much as possible. And this doesn&#8217;t just apply to developers but to technologies as well. I believe there&#8217;s a reason that Java largely didn&#8217;t survive as a pure front-end technology, and why there hasn&#8217;t been a pig push by the community to bring native Ruby processing to the browser. These technologies have their place, but the browser is not that place.</p>
<p>Whether you like JavaScript or not, it&#8217;s quite clear that it is uniquely and best positioned to service all the needs that the UI layer needs. And as you&#8217;ll see in a little bit, that means both in browser and on the server. You may not ever (want or need to) re-write your hundreds of thousands of lines of Java, but I hope maybe you&#8217;ll consider delegating your UI code to the technology that rules the UI. </p>
<h3>&#8220;Both-enders&#8221;</h3>
<p>I can just hear some of you right now: you&#8217;re the ones who wear both the hat of front-end developer and back-end developer (sometimes at the same time). For you, it&#8217;s no big deal at all to &#8220;context switch&#8221; mentally and use back-end technology (like a JSP taglib) to generate your front-end. In fact, if you&#8217;re not a <em>specialist</em> in UI technologies, that may be more comfortable and productive for you to do so.</p>
<p>I don&#8217;t claim that I can convince you otherwise. But let me just submit to you this suggestion: is it possible that you might be more efficient at your UI hat tasks if you didn&#8217;t have to concern yourself at all with back-end architecture issues? And vice versa, would your back-end work be more fun and efficient if you didn&#8217;t have to constantly worry about markup, box model quirks, or cross-browser JavaScript&#8217;ing? </p>
<p>I think it would. In fact, I&#8217;m almost certain of it (at least the UI hat side of things). I&#8217;ve worn both hats many times in many different jobs. And I can tell you that unequivocally, I was noticeably more efficient when I had the ability to only wear one hat any given time. What is good for the back-end is often times irrelevant (or bad) for the UI, and vice versa. They are two entirely different disciplines, and it&#8217;s time we admit that. Not that you can&#8217;t do both, and effectively, but just that you can&#8217;t do both <em>at the same time</em> effectively.
</li>
<li><strong>Stop meddling in <em>my</em> code</strong>: Probably my biggest issue with how most frameworks and platforms approach templating is that the templating engine is deeply embedded in, and hopelessly intertwined with, the back-end technology. This invariably leads to far too often bending/breaking the fundamental rule of the MVC pattern (keep the View, Controller <em>and</em> Model <strong>separate</strong>).
<p>For instance, consider PHP as a simple example. PHP <em>is</em> a templating engine (if you weren&#8217;t already aware). It allows you to take a predominantly HTML file and litter any manner of PHP code logic all throughout it. <strong>THIS IS NO BETTER THAN THE SPAGHETTI CODE OF QBASIC FROM 20 YEARS AGO.</strong> You actually have to fight hard against these urges (and pretty much every tutorial on the web), and go to great lengths to keep your templates free from such mess.</p>
<p>And why go to this trouble, you may wonder? Let me give this example:</p>
<pre class="code">
&lt;div id="#controls">
   &lt;?php if ($user->IsLoggedIn() &#038;&#038; $user->CanPublish()) { ?>
      &lt;a href="publish.html">Publish&lt;/a>
   &lt;?php } ?>
&lt;/div>
</pre>
<p>Seems harmless enough, right? <strong>WRONG.</strong> This is pure and undefiled evil. You think that just because you put the login session logic and access control logic into your Model (wait, shouldn&#8217;t that <em>actually</em> be in the Controller???), and you merely call and use those methods in your template, you&#8217;ve achieved separation? <strong>WRONG.</strong></p>
<p>Why do I feel so strongly? Because this pattern is blatantly opening up the doors to putting Controller (and Model) logic right inside the View. First of all, your front-end developer (if that&#8217;s not also you Mr. Back-end Engineer) has to know something about your back-end technology (PHP in this case) &#8212; and in some cases, they need to know <strong>a lot</strong> about the back-end to even accomplish a small UI task. This is <em>probably</em> not his or her core skillset (see #2 above), so it&#8217;s bound to slow down the efficiency of UI work. </p>
<p>Also, you have now tied business logic into your View, which is against proper patterns we all learned in Software 101. Consider this scenario (which is so common it&#8217;s almost self-obvious): The View developer writes code like the above. Then he leaves the company. </p>
<p>6 months later, a back-end developer goes through and refactors the Model. He decides for one reason or another that Access Control Permissions are now going to be exposed in the Model (ie, across all the back-end code) as a bitmask property upon which efficient bitwise operators (| &#038;) can be used to figure out permissions. Because they want to keep the back-end code pure and efficient, and don&#8217;t want unnecessary methods literring the Model, they <strong>remove</strong> the <code>$user->CanPublish()</code> method. No problem, right? We just do a grep/code search and find all instances of CanPublish(), and we change that code to instead be <code>($user->perms &#038; USER_CAN_PUBLISH)</code>.</p>
<p>Ugh. If this doesn&#8217;t scream out at you as bad, I don&#8217;t know what planet you develop on. It gets worse. 6 months later, the back-end developer quits, and shortly thereafter, the business folks decide that a user must have both USER_CAN_PUBLISH permission and <strong>not</strong> <code>($user->restrictions &#038; USER_IS_DISABLED)</code>. I bet at this point, the new back-end developer instead gives in and creates a method <code>$user->CanPublishAndEnabled()</code>. Yet more Controller/Model logic hopelessly embedded in the View. And yet another round of View refactorings. I bet your front-end developers (who don&#8217;t know much PHP) are getting annoyed by now. Are you seeing the pattern?</p>
<p>What if instead, there was a pre-agreed-upon <em>Boolean</em> property in the View data (ahem, not Model), called &#8220;allow_publish&#8221;. The Controller takes care of setting that property (with whatever logic is appropriate at that moment in time) before it invokes the View, and it just passes along that Boolean flag to the View. Then, no matter what kind of back-end refactorings or logic changes occur, the View always look like this:</p>
<pre class="code">
&lt;div id="#controls">
   &lt;?php if ($data["allow_publish"]) { ?>
      &lt;a href="publish.html">Publish&lt;/a>
   &lt;?php } ?>
&lt;/div>
</pre>
<p>The difference may seem subtle, but it&#8217;s actually enormously important. While I&#8217;d definitely call this an improvement, there&#8217;s definitely more we can (and should) try to achieve.</p>
<h3>But, my MVC can do that</h3>
<p>The point is not <em>really</em> whether your current environment <em>can</em> do what I&#8217;m suggesting. The point is that it probably <em>isn&#8217;t</em>, and moreover, it probably feels easier to all involved if it doesn&#8217;t. Otherwise, you probably wouldn&#8217;t still be reading this article, because you&#8217;d be so furiously effciently coding away in your utopian development environment and would have no desire to read my crazy ramblings on the topic!</p>
<p>I believe we need to encourage Templating Engine solutions to be absolutely minimalist on the amount of &#8220;programming&#8221; they allow in the Views. The bias should be: allow only the bare minimum of logic as is necessary to select templates and fill them with data. If it&#8217;s any harder than that, then it&#8217;s logic that belongs back in the Controller (or deeper). Sure, you need basic things like boolean logic for selecting sub-templates, simple looping constructs, and such. But you don&#8217;t need the ability to call functions, invoke complicated, deep instantiation heirarchies of mixed Models, run math computations, or any of that non-sense. <strong>Remember</strong>: Jet-liner to the corner store.
</li>
</ol>
<h2>Nodding off</h2>
<p>OK, so at this point, you must be exhausted reading this post. I&#8217;m exhausted writing it. I promise I&#8217;m gonna wrap up quickly. I know it&#8217;s a lot of information to take in, but I&#8217;m intensely passionate that it needs to be said, and these questions and issues <em>need</em> to be addressed.</p>
<p>This article has thus far been almost entirely me laying out the reasons why I didn&#8217;t like <em>most</em> of the templating solutions that are common across the vast majority of web application frameworks and platforms. This is by far not an exhaustive list of the problems, but those 3 points above are a pretty good summary of the <em>types</em> of problems motivating me to find and present another way.</p>
<p>So, if you&#8217;re still with me after all that, let me try to briefly explain how I believe HandlebarJS addresses these concerns (and others).</p>
<h2>Finally, some Handlebars</h2>
<p>HandlebarJS gets its name as the upside down mustache (from <a href="http://github.com/janl/mustache.js">MustacheJS</a> templating). The { and } are the things of which we speak.</p>
<p>Here&#8217;s what you should know about HandlebarJS:</p>
<ol>
<li>HandlebarJS is <em>entirely</em> written in JavaScript. In fact, it&#8217;s entirely written in a manner that allows it to run in either a synchronous or asynchronous environment, either in the browser or on the server (using any of several available server-side JavaScript environments). This allows the exact same code base to run either in browser or on server. Period. Doesn&#8217;t get any more DRY than that. You can do templating in either place, or both, as your application requires.
<p>It&#8217;s small and portable and so should be suitable for your templating tasks in a wide variety of JavaScript friendly environments, including even (and especially) mobile.
</li>
<li>It follows naturally that since the HandlebarJS code is portable and identical both in browser and on server, the templates themselves are also identical. Absolutely. The templating &#8220;language&#8221; is simple but expressive and capable of any tasks you should rightly tackle with templating. And so you can write your templates once, and run/interpret them in any HandlebarJS capable environment. Again, this is <em>really</em> DRY.
</li>
<li>HandlebarJS accepts JSON data, and only JSON data, as its input. This means that any platform/environment which can serialize its Model/data down to JSON can send that data to a HandlebarJS instance and get back a processed template View output. Pretty much every language on the planet has JSON serialization/de-serialization support built-in (or at least available easily). JSON data is also the <em>only</em> format of data that is fully and natively portable from server to browser.
<p>That&#8217;s right, some browsers (and clients) don&#8217;t natively understand XML even, but they <em>all</em> understand JavaScript, and thus all understand JSON data. Why go to the inefficient trouble of wrapping your data up in some other non-natively-parseable data abstraction? Just use JSON. Trust me, there is no other format better for the task.
</li>
<li>HandlebarJS is built with simplicity and efficiency in mind. The templating language is as simple as possible to get the job done. It doesn&#8217;t give you too much rope to hang yourself. You really can&#8217;t embed Controller or Model logic in these Views.
<p>Also, HandlebarJS compiles templates from their text files into executable JavaScript snippets. This &#8220;compilation&#8221; can be done on the fly (in either browser or server) if necessary, or it can be done as part of a build-process to increase efficency. HandlebarJS will operate the same functionally regardless of whether it&#8217;s dealing with pre-compiled templates or needing to compile them on-demand.
</li>
<h2>Fin</h2>
<p>OK, that&#8217;s it, I&#8217;m done, I promise. I hope by this point you&#8217;re at least convinced it might be a good idea to take a look at HandlebarJS. Even if you are still certain that your existing application architecture is sufficient and won&#8217;t need to change, perhaps you might consider exploring if just the View portion can, in whole or in part, be separated off and delegated to a HandlebarJS instance. </p>
<p>If you only want to use HandlebarJS in the browser, you can do so without any architectural/server changes at all. Just drop it into an existing page and start converting your existing templates one-at-a-time. See how easy it is!</p>
<p>And absolutely the only required dependency for HandlebarJS (on the server) is a simple server-side JavaScript environment (many options are available). In fact, keep an eye for the next blog post here, as I will be discussing my brand new released <a href="http://github.com/getify/BikechainJS">BikechainJS</a>, which is a SSJS wrapper around the V8 JavaScript engine, allowing drop-dead simple JavaScript execution on the server. HandlebarJS and BikechainJS are specifically built to be simple and compatible.</p>
<p>Seriously, stop reading this blog post <strong>now</strong> and go <a href="http://github.com/getify/HandlebarJS">check out HandlebarJS</a> &#8212; isn&#8217;t it about time for you to grab your UI by the &#8220;Handlebar&#8221; and make it do what you want?</p>
<div><a class="addthis_button" href="//addthis.com/bookmark.php?v=250" addthis:url='http://blog.getify.com/grab-ui-by-the-handlebar/' addthis:title='Grab UI by the Handlebar '><img src="//cache.addthis.com/cachefly/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a></div>]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/grab-ui-by-the-handlebar/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Content Delivery Network via getiblog.2static.it

Served from: blog.getify.com @ 2012-05-18 09:56:14 -->
