<?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; architecture</title>
	<atom:link href="http://blog.getify.com/tag/architecture/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.getify.com</link>
	<description>open-source, performance, javascript &#38; ui musings</description>
	<lastBuildDate>Mon, 23 Aug 2010 20:50:24 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Why Node.js rocks the middle-end</title>
		<link>http://blog.getify.com/2010/07/why-node-js-rocks-the-middle-end/</link>
		<comments>http://blog.getify.com/2010/07/why-node-js-rocks-the-middle-end/#comments</comments>
		<pubDate>Thu, 15 Jul 2010 21:08:20 +0000</pubDate>
		<dc:creator>getify</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[UI Architecture]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[middle-end]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[ui]]></category>

		<guid isPermaLink="false">http://blog.getify.com/?p=467</guid>
		<description><![CDATA[If you&#8217;re even moderately involved in the JavaScript world these days (and you probably are if you&#8217;re reading this blog) you would have to be dead asleep to not have noticed and heard some of the hype and celebration for the poster-child for server-side JavaScript: Node.js. 
I regularly follow the chatter on the interwebs, and [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re even moderately involved in the JavaScript world these days (and you probably are if you&#8217;re reading this blog) you would have to be dead asleep to not have noticed and heard some of the hype and celebration for the poster-child for server-side JavaScript: <a href="http://nodejs.org/">Node.js</a>. </p>
<p>I regularly follow the chatter on the interwebs, and I&#8217;m amazed and thrilled at just how much gravity Node.js has accumulated in terms of developer excitement and <em>actual</em> project input. In fact, in some ways, the Node.js ecosystem of companion projects is even more awesome than Node.js itself! It&#8217;s a fantastic example of how the community was desperate for something (we didn&#8217;t even know exactly what) and how well we quickly rallied around <em>it</em> when we finally found it. It&#8217;s plainly obvious that server-side JavaScript is an idea whose time has come, and Node.js, in many ways, will take us there.</p>
<p>This post is an attempt to put my little niche spin on what Node.js <em>could</em> mean for someone wanting to tackle re-architecting <a href="http://middleend.com">the middle-end</a> of their web application.</p>
<h4>What is Node.js?</h4>
<p>In the broadest terms, Node.js is an application server platform. It&#8217;s actually a server-side JavaScript execution environment (roughly similar to something like Narwhal) wrapped around the V8 JavaScript engine. But it&#8217;s a very special type of environment compared to other options in this space. <strong>Node.js is completely asynchronous.</strong> This means that everything you do in Node.js, you do in terms of asynchronous-friendly API&#8217;s, like network calls, file i/o, etc.</p>
<p>But even more important is that Node.js is specially designed to operate as an independent and fully-functional network server. What do I mean by this? Node.js&#8217; flagship capability, and indeed how most people use it, is its ability to &#8220;listen&#8221; for incoming requests on a particular network port (like port 80 for web traffic) and service those requests like a web server like Apache or IIS might do. <strong>In other words, Node.js at its most optimal is a drop-in replacement for your current web server.</strong> And it wraps in a fully capable application server (using JavaScript) automatically. Cool, huh?!</p>
<p>Because Node.js is asynchronous, it doesn&#8217;t operate under the covers at all like other web servers do. Instead, it operates in an &#8220;evented processing loop&#8221; where it is simultaneously and asynchronously listening for incoming connections, firing off processing to handle each connection, and then &#8220;listening&#8221; for those processing contexts to finish to hand the results back to the requesting connection stream. The result is that in many use-cases, Node.js is able to achieve mind-blowing amounts of parallel processing and throughput compared to more standard web servers like Apache.</p>
<p>Bottom line: Node.js&#8217; core competency is to take a server-side JavaScript application server environment and wrap it cleanly around a super-efficient asynchronous network server. In most respects, this is simply the most efficient server-side JavaScript environment you&#8217;re likely to ever find, and it allows JavaScript to compete head-to-head with even optimized, compiled binary alternatives.</p>
<h4>Is it for me?</h4>
<p>Up until now, every thing I&#8217;ve spoken about and written regarding middle-end architecture and server-side JavaScript has been conspicuously silent on the topic of Node.js. There is good reason for that, but I only want to touch briefly on it here, by means of comparison. The next post will dive into this much more thoroughly.</p>
<p>The utter awesomeness that is Node.js comes with a <em>price</em>. For most developers who are hacking and tinkering with new ideas all the time, this price is mere &#8220;pocket change&#8221; and that&#8217;s probably the biggest reason why the Node.js community has grown so quickly and so broad. But there is a &#8220;silent majority&#8221; lurking out there for whom the Node.js price may not be quite so trivial. What is this <em>price</em>? Infrastructure.</p>
<p>Thus far, my focused efforts have been on finding the lowest possible barrier-of-entry into the server-side JavaScript world. By barrier-of-entry, I mean the least amount of footprint/impact on existing infrastructure/architecture and to existing maintenance and support/IT staff. The current fruits of that labor has been the humble <a href="http://github.com/getify/BikechainJS">BikechainJS</a> server-side JavaScript project. </p>
<p>I shyed away from presenting my middle-end ideas in the context of Node.js because there are many who cannot necessarily proceed under the guise of replacing their top-level web server (along with all its associated dependencies, modules, configurations, etc) with an entirely new (and fundamentally paradigm-shifting) solution like Node.js. No doubt we&#8217;d mostly all agree that it would be exciting and probably even more efficient, but the slow-to-change momentum of existing applications, teams, infrastructure, maintenance, reliability, and IT support staff have a noticeably chilling effect on the hyper-excited server-side JavaScript movement.</p>
<p>It was my goal that something like BikechainJS, with its synchronous, per-request paradigm, could squeeze much more nimbly into existing application infrastructure, even at the cost of the wins from Node.js&#8217; performance.</p>
<h4>But Node.js is just so damn awesome!</h4>
<p>That&#8217;s absolutely true. And I&#8217;ve come to believe that the awesomeness of Node.js does not <em>have</em> to be mutually exclusive of the middle-end architectural ideas I&#8217;m advocating for, nor does it <em>have</em> sit out of reach from so many existing web applications, dev teams, and web shops.</p>
<p><strong>Node.js <em>can</em> (and perhaps should!) be the magic key to unlocking the full potential of your application&#8217;s middle-end.</strong></p>
<p>What if we can have our cake and eat it, too? What if we can find a clean way to plug Node.js into the existing infrastructure of our web applications, and at the same time give it the power to revolutionize our middle-end tasks? We&#8217;d get exponentially better performance <em>and</em> revolutionary better code architecture. That idea is just so full of win it&#8217;s hard to type without going nuts!</p>
<h4>Augment, not replace</h4>
<p>My biggest mental sticking point all along with Node.js has been the (im)practicality of asking an existing application to just simply swap out its entire web server tier for Node.js. I explored even the idea of running Node.js in a more limited, synchronous, per-request (CGI-like) context, but quickly found that was like trying to teach a bird to swim.</p>
<p>Then it hit me. The best way Node.js revolutionizes the middle-end of your existing/legacy web application is if you build your middle-end Node.js-based and insert it wholly into the stack in between the browser and your existing server.</p>
<p>In this respect, your middle-end Node.js layer becomes a &#8220;proxy&#8221; (or &#8220;web balancer&#8221;) server of sorts, sitting in front of your existing web server. All you have to do is bring up a Node.js VM/server instance (even cloud-based!) and direct all your primary traffic to that instance first. Then, you build out your middle-end architecture, doing templating, URL routing, data validation, and all the other tasks, as necessary, in your Node.js server-side JavaScript, and finally, you hook Node.js up to ferrying requests back over to your existing application server.</p>
<p>In this blind-proxy model, you start off with a dumb pass-thru of all your application&#8217;s requests, and then one-by-one you can inject some intermediate middle-end logic using the server-side JavaScript. For instance, <a href="http://blog.getify.com/2010/07/how-to-begin-your-middle-end/">as I talked about before</a>, you can start doing data-validation of inbound data fields using your Node.js-driven JavaScript. And then you can move on to evolving your templating into a true middle-end task in your JavaScript. And so on.</p>
<h4>Win, win, win</h4>
<p>The benefits of this approach are hard to explain by mere words. First and foremost, you will see an insane jump in the request/response performance simply by letting Node.js manage your application&#8217;s front line web server handling. But equally important, you gain invaluable flexibility to start converting your thick back-end into a well-crafted middle-end/back-end approach. And you don&#8217;t have to change very much of your existing infrastructure at all.</p>
<p>This is what I like to call a &#8220;middle-win&#8221; scenario! Node.js really rocks the middle-end.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/2010/07/why-node-js-rocks-the-middle-end/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Middle-end your CMS</title>
		<link>http://blog.getify.com/2010/07/middle-end-your-cms/</link>
		<comments>http://blog.getify.com/2010/07/middle-end-your-cms/#comments</comments>
		<pubDate>Thu, 15 Jul 2010 14:54:34 +0000</pubDate>
		<dc:creator>getify</dc:creator>
				<category><![CDATA[UI Architecture]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[cms]]></category>
		<category><![CDATA[middle-end]]></category>
		<category><![CDATA[ui]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://blog.getify.com/?p=452</guid>
		<description><![CDATA[Continuing my ongoing efforts to simplify the middle-end, this post will focus on a high-level discussion of how you might start to adjust and adapt the middle-end concepts (CVC pattern) for use in a CMS environment, for instance a WordPress blog.
As with everything else I&#8217;ve presented so far, I have no cleanly packaged &#8220;install&#8221; you [...]]]></description>
			<content:encoded><![CDATA[<p>Continuing my <a href="http://blog.getify.com/2010/07/how-to-begin-your-middle-end/">ongoing efforts to simplify</a> the <a href="http://blog.getify.com/2010/07/what-exactly-is-the-middle-end/">middle-end</a>, this post will focus on a high-level discussion of how you might start to adjust and adapt the middle-end concepts (CVC pattern) for use in a CMS environment, for instance a WordPress blog.</p>
<p>As with everything else I&#8217;ve presented so far, I have no cleanly packaged &#8220;install&#8221; you can grab to solve your woes. On the contrary, I believe that pre-packaged frameworks and modules <em>usually</em> lead us to the mess we&#8217;re already in &#8212; that is, they tend to hide from the developer the very details we so critically need to get our brains wrapped around and our hands in control of.</p>
<p>Re-architecting the middle-end of your site/application will never be as easy or as sexy as just dropping in a new module/framework, because the point is to tailor your middle-end <em>specifically</em> to your own needs, which is opposite of the goal of most turn-key frameworks that &#8220;do it for you&#8221;.</p>
<p>Whenever I talk about code or about possible ways to address these concerns, that talk is nothing more than presenting reference implementations as starting points for what <em>your</em> system will need. <strong>The middle-end is a pattern, not a package.</strong></p>
<h4>Steep mountain</h4>
<p>I consider myself pretty well-versed in PHP and application coding, from the UI down to the database. But when I started thinking about these ideas for the middle-end, I admit the most daunting task I could come up with is how to apply them to a CMS like WordPress.</p>
<p>What I know from the few times I&#8217;ve tried to customize WordPress is this: it&#8217;s great and easy if there&#8217;s already a plugin available, but otherwise, you&#8217;re in for some long head-scratching nights. It&#8217;s not that WordPress isn&#8217;t flexible &#8212; there&#8217;s lots of hooks in there and you can do a lot of stuff <em>if you know how</em> &#8212; it&#8217;s that the <em>knowing how</em> is quite a challenge because of how sophisticated the system is and how many different flexibilities it needs to accommodate for.</p>
<p>So, how might we take our first steps to climb this challenging mountain of a task?</p>
<h4>Preparation</h4>
<p>First, let&#8217;s make sure we are clear on what it is we want to do with WordPress CMS to adapt it to be &#8220;CVC-friendly&#8221; (that is, properly architected for a well-formed middle-end).</p>
<p>As I&#8217;ve mentioned before, a proper middle-end will give you complete and custom control over things like templating, URL routing, data validation, data formatting, etc. Moreover, I&#8217;ve posited that the middle-end is this interesting beast in that it straddles the fence between browser and server &#8212; many middle-end tasks need to be performed in both places. </p>
<p>And because there are many of these <em>shared tasks</em> between both environments, having to code solutions twice (once in JavaScript for the browser, a second time in your back-end language of choice&#8230; PHP in this case) is both time consuming and brittle. For many middle-end tasks, it would sure be nice if we could DRY (don&#8217;t repeat yourself) code the tasks once and use them in both places. That&#8217;s a big motivation for all my middle-end rattling.</p>
<p>But, does a WordPress blog really need to do all that? In some respects, no it doesn&#8217;t. A typical WordPress blog is not necessarily what I&#8217;d characterize as a full-blown web application. By far, the most important thing for a WordPress blog is usually the content, not necessarily the intricate user-interactions with that content.</p>
<p><strong>But that doesn&#8217;t mean a good middle-end is <em>unimportant</em> to your WordPress blog.</strong> In this case, the ability to control certain middle-end tasks for web performance optimization efforts is likely going to be our primary motivating factor. </p>
<p>For instance, let&#8217;s say we just want to gain more custom control over how resources (JS, CSS, etc) are packaged together and delivered to the browser. The reason this is so common a frustration in CMS&#8217;s like WordPress is the tendency of many individual separate plugins to all add their own script/css dependencies to the document in various strewn-about ways. There <em>is</em> a central system in WordPress that should make this easier, but many plugins don&#8217;t use it well. And even the central system itself is not quite good enough for what we really need.</p>
<p>So, rather than focusing so much on creating a server-side JavaScript driven middle-end whose code can run in server and browser alike, we&#8217;re going to take a step back and think about how we could architect our WordPress blog so that these tasks we want to do are easy enough to be practical and efficient without knowing all the intricate details of a very complex &#8220;hooks&#8221; and plugins system. <strong>Server-side JavaScript is one option we could choose for that task, but by no means required.</strong> Much more <em>importantly</em> will be that we focus on the easiest path to achieve a well-formed and flexible middle-end.</p>
<h4>Option 1</h4>
<p>Our first option is to get really familiar with how the internals of WordPress work. I know from personal experience that such a task can be both a blessing and a curse, both fruitful and frustrating. As I said before, my strong preference would be to find an existing plugin that does exactly what I want it to do. But with the overwhelming popularity of something like WordPress, that can truly be like finding the needle in the haystack.</p>
<p>Usually, when I decide I want to do something new on my WordPress blog, I go spend several hours searching and researching various plugins. Then I&#8217;ll pick one or two to download and try out. I install them, start messing with configuration, and usually find that it&#8217;s <em>almost</em> what I want but not quite. Could I settle? Sure. But I&#8217;m a coder, that&#8217;s not likely to happen!</p>
<p>So then, I may try a couple of other options, only to be similarly frustrated. I may then start trying to google and dig through WordPress documentation, comparing what I see in the code for the plugin to what I read about on the web. And, being a decently confident PHP coder (by no means an expert!), I may start trying to tinker with the code to tweak it to what I want.</p>
<p>And sometimes this will work out. But now I have a problem (that I won&#8217;t realize until a month later). I&#8217;ve customized a plugin&#8217;s code for my own needs, and I&#8217;ve now forever damned myself to having to remember those customization patches and re-apply them every single time that plugin notifies me of a new release. A number of my plugins update themselves quite regularly, so this becomes a real pain.</p>
<p>For instance, right now, I have 2 plugins that have notified me of an update, but I&#8217;ve resisted doing the update because I don&#8217;t want to spend the 10 minutes to go back in and refresh myself on what customizations I did. I know in this case the customizations I did referred specifically to our task of customizing how JS and CSS resources are packaged and loaded. But it&#8217;s still time and hassle that I don&#8217;t want to spend. And so I miss out on the benefits of the update until I pay that price.</p>
<p>I am not going to sugar coat it: <strong>this process sucks.</strong> Even if I <em>do</em> figure out how to customize a plugin for my own needs, which in and of itself takes a lot of effort, then I have to keep spending that effort over and over again every time an update comes out.</p>
<p>Bottom line: option 1 is possible, and it&#8217;s quite likely that for most middle-end tasks, you could figure out a way to hack around existing plugins to bend WordPress to your will. But unless you&#8217;re a WordPress guru (I clearly am not) and have the time and inclination to regularly hack on it, the benefits of doing so <strong>are probably not worth it.</strong></p>
<h4>Option 2</h4>
<p>Out next option would be to go to the other end of the spectrum entirely, and not do anything inside of WordPress. We could, for instance, set up a &#8220;proxy&#8221; server (of sorts) which all browser-initiated web requests get sent to first, and that &#8220;proxy&#8221; would then make a sub-request to WordPress to get the desired page/content.</p>
<p>What this approach would allow us to do is basically &#8220;post-filter&#8221; all the content before it actually goes out to the browser. For example, we could take the HTML of the page response, and parse through it looking for our &lt;script> and &lt;link> tags. When we find them, we could remove them from the HTML stream (just text at this point!), and then append to the HTML document a more optimized set of resource loading commands.</p>
<p>Basically, we could find all script tag references, open the .js files they refer to, concat them all together into a single .js file which we cache ourselves in our proxy&#8217;s control, and then add a single &lt;script> tag back to the HTML document referencing that new concatenated file. A similar process could be done for all our CSS resources.</p>
<p>You may even want to get more elaborate (as I would advocate) and instead of compiling like resources into a single file, compile them into 2 or 3 files, and use dynamic loading techniques in the browser to load them in parallel, even further speeding up the page-load optimization. One such dynamic loader you could use would be <a href="http://labjs.com">LABjs</a>, <em>the performance script loader</em> that I built.</p>
<p>But let&#8217;s not kid ourselves: this is a drastic approach. Setting up an entirely separate web server (or web server instance/VM) <em>just</em> so we can post-process some HTML markup!? I&#8217;m not saying this wouldn&#8217;t work for some people, but I am thinking that it&#8217;s probably something that has its own set of daunting challenges and extra &#8220;costs&#8221; (especially maintenance) involved. </p>
<p>Not only is it drastic, it&#8217;s also more brittle. No matter how good your coding skills are, parsing through arbitrarily generated and complex HTML markup and modifying it on the fly is <em>going to be difficult to do, at best.</em> And it&#8217;s quite easy for it to break if your HTML generation routines (your blog) change how they do things in a way your &#8220;proxy&#8221; was not expecting.</p>
<p>Bottom line: option 2 is also possible, but probably not exactly what we want or need.</p>
<h4>Option 3</h4>
<p>For our last option, let&#8217;s dial things back just a little bit and be a little more realistic. Let&#8217;s not try to fight against WordPress, but to work with it. What I mean is this: WordPress is very capable at doing what it does, and if someone has already built a plugin that suits your needs, by all means use it. But the other thing that WordPress does (and I think decently well) is let us <em>completely</em> control the ultimate output of our blog engine using the Themes (templating) system.</p>
<p>So maybe we could try this: let WordPress do what it does best, as a good solid CMS. But run it as essentially a &#8220;headless&#8221; black box application and practically ignore any presentational stuff that it wants to do. We can ask WordPress for content/data, but we can let the middle-end layer do what it is best suited for, which is handling these various middle-end tasks.</p>
<p>What I&#8217;m about to suggest may seem radical&#8230; but read the sentence a few times and let it sink in. <strong>Make a theme for your WordPress blog which does <em>nothing</em> of generating HTML markup, and <em>only</em> formats necessary data/content into JSON.</strong></p>
<p>That&#8217;s right! Reduce the templating/themeing system of WordPress to nothing more than a JSON serializer for the relevant content and data to construct your page. What data? How about an array of all the scripts and css files. How about meta data like the page title, etc. How about the raw content for the blog post the page displays.</p>
<p>What would we do with that data and content in JSON form? We could have a separate middle-end layer that took the JSON and did something useful with it. That middle-end layer <em>could be</em> server-side JavaScript. But it also could just as easily be more PHP (outside of and strictly separate from your WordPress blog engine). Or it could be some other language you are more comfortable with.</p>
<p>But whatever language your middle-end is written in, you would do some very basic things:</p>
<ol>
<li>Take the list of .js and .css resources in the JSON array properties, and perform the above suggested logic like concatenation, caching, etc.</li>
<li>Take any meta-data and properly &#8220;format&#8221; it for HTML use, such as converting special characters to HTML entities, etc. Or, perform &#8220;internationalization&#8221; formatting on your data/content.</li>
<li>Perform any other middle-end suitable tasks on the data and content as necessary.</li>
<li>Lastly, pass that data/content into your templating engine of choice, and then send the output directly to the browser.</li>
</ol>
<p>You see, we don&#8217;t <em>have</em> to change much about how WordPress does its magic to start having more proper control over the middle-end. And we don&#8217;t even have to venture into server-side JavaScript to do it. All we have to do is trick WordPress into giving us data and content in a friendly way that allows us to do what we want with it. </p>
<p>And the Theme/template system makes that really easy. Nothing about the state or complexity logic that WordPress is doing can&#8217;t be somehow down-formatted into data/content in JSON form, and so we&#8217;d practically lose nothing of the functionality of WordPress, but gain lots of control in the areas we need it most.</p>
<h4>Conclusion</h4>
<p>CMS&#8217;s are a fact of life on the web. They sit somewhere between a full web application and a basic content web site. As such, there are reasons why we can benefit from a more well-formed and properly architected middle-end. But it doesn&#8217;t have to take wholesale hackery on our blog engine to do so. There are ways to work with it to massage the content/data in such a way that we can layer in a middle-end without too much of a radical change to the architecture.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/2010/07/middle-end-your-cms/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How to begin your middle-end</title>
		<link>http://blog.getify.com/2010/07/how-to-begin-your-middle-end/</link>
		<comments>http://blog.getify.com/2010/07/how-to-begin-your-middle-end/#comments</comments>
		<pubDate>Tue, 13 Jul 2010 15:59:15 +0000</pubDate>
		<dc:creator>getify</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[UI Architecture]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[middle-end]]></category>
		<category><![CDATA[ui]]></category>

		<guid isPermaLink="false">http://blog.getify.com/?p=443</guid>
		<description><![CDATA[In the previous post, I distilled down into a simple definition what I call the &#8220;middle-end&#8221; of web applications and also my arguments for why it&#8217;s so vitally important that it be a separate and distinct layer rather than an assumed and forgotten tag-along as it is in many common frameworks/platforms.
But upon further discussion and [...]]]></description>
			<content:encoded><![CDATA[<p>In the previous post, I distilled down into a simple definition what I call the <a href="http://blog.getify.com/2010/07/what-exactly-is-the-middle-end/">&#8220;middle-end&#8221; of web applications</a> and also my arguments for why it&#8217;s so vitally important that it be a separate and distinct layer rather than an assumed and forgotten tag-along as it is in many common frameworks/platforms.</p>
<p>But upon further discussion and reflection, I realize that it&#8217;s tempting to read the ideas I have presented and assume that I&#8217;m suggesting a more comprehensive and wide-spread re-architecture effort than I really am. The last thing I would want to do is leave you with the impression that this is an intimidating and complex task to undertake. The tasks I&#8217;m advocating for are quite the opposite: they are small, independent, modular, and intended to be rolled into your application in manageable, evolutionary chunks.</p>
<p>So this is just a short follow-up to that post to explain how I feel most web applications could begin the task of redefining their &#8220;middle-end&#8221; in a more well-formed way, with minimal impact to existing architecture.</p>
<p><strong>The task of re-architecting your middle-end begins with a couple of very simple, incremental steps, not a wide-spread rewrite as it may seem.</strong></p>
<h4>Color by numbers</h4>
<p>Let&#8217;s take data validation for example. First let me define what I mean by data validation: the set of <em>stateless</em> rules which are applied to one or more pieces of data to ensure that the input into the application is safe, reliable, and appropriate.</p>
<p>The most common scenario this is seen in would be form validation. Consider a contact form that requests a visitor&#8217;s first and last name, email address, favorite color, and any additional comments. The first and last name fields are text input, and are required. They must both be between 5 and 25 characters. The email field is also text input, must be 8 to 100 characters, and must additionally &#8220;look&#8221; like a valid email (passing some arbitrarily complex regular expression matcher). The color field is a drop-down, which by virtue of the UI paradigm is constrained to a pre-defined set of options. The additional comments are optional, but if present must not contain any HTML.</p>
<h4>Stateless Data Validation</h4>
<p>Data validation in this context would entail all of these aforementioned rules. It could also entail data integrity checks, like for instance asking something (totally contrived for this discussion) like &#8220;if the first name is John, the last name cannot be Brown&#8221;.</p>
<p>However, something like enforcing that the email address was &#8220;unique&#8221; in our database (meaning we&#8217;ve never heard from this person before), or that the email was not already on a blocked &#8220;black list&#8221; as a spammer &#8212; those tasks would not be <em>stateless</em> data validation checks, but would instead require stateful back-end business logic. That would not be something we&#8217;d want to do wholly in the UI layer (maybe via a round-trip Ajax request, etc).</p>
<p>The point is that stateless data validation/integrity checks are agnostic of the environment or the state of the application. The check is blindly applied to a piece of data, and the result is binary true or false &#8212; either it passed or it didn&#8217;t. This means that such code can be written to act upon a data structure (like JSON) and be completely ignorant of where the data came from. <strong>This is very important.</strong></p>
<p>Because we know that data validation is important to User Experience, we often write those rules in JavaScript, and run them in the browser while the user is interacting with the UI/form. But because as good Computer Scientists we know that no UI can be trusted, we also know that the same rules need to run on the server on any inbound data. </p>
<p>This is where trouble usually starts happening. We re-write all our validation rules a second time, this time in another language like PHP or Java. We&#8217;ve made a second copy of that code/logic, and we&#8217;ve forever cursed ourselves with more complicated code maintenance.</p>
<h4>Another way?</h4>
<p>What if, however, we could write the stateless data validation rules in JavaScript, to operate on a JSON data structure with one or all fields present/populated, and we could run the <em>exact same code</em> in both the browser and on the server? That would achieve an unprecedented level of DRY (don&#8217;t repeat yourself) coding in this context!</p>
<p>Is there any reason why our application, regardless of what language/platform it is, <em>couldn&#8217;t</em> entrust the tasks of stateless data validation to a server-side JavaScript module? I&#8217;d say, plainly, <strong>no!</strong>. </p>
<p>If the data validation logic ran on the server, in a trusted environment, what difference would it make if it was JavaScript or PHP doing the checking? The difference (for the better) is that this code logic would be write-once-and-reuse, and that&#8217;s a huge improvement in maintenance.</p>
<p>In the browser, you would have controller logic that would take one or more data fields from the &lt;form> and stuff them into a data structure (JavaScript object and properties). Then, you would pass that data into a set of JavaScript code logic that ran the rules against the appropriate properties, and spit out true/false answers.</p>
<p>On the server, you would take inbound data, either already formatted as JSON (preferably) or in key-value pairs that you could easily serialize to JSON, and then pass that inbound data directly into the same code.</p>
<h4>This still seems complex</h4>
<p>All you really need to accomplish this is to be able to execute some very basic JavaScript on your existing application server. There are a number of options available, ranging in complexity and scope from Node.js to Narwhal, etc. Another, much more stripped down option is my environment, <a href="http://github.com/getify/BikechainJS">BikechainJS</a>. BikechainJS is a single executable file environment wrapped around the V8 JavaScript engine. It&#8217;s designed to be run in &#8220;CGI mode&#8221; &#8212; in other words, per-request, on-demand &#8212;  in existing web application frameworks.</p>
<p>So, using something very simple like BikechainJS, you could easily set up your existing web application to run a BikechainJS execution to do the data validation tasks I just mentioned.  You&#8217;d simply take a single data input endpoint in your existing application (like the action that responds to your contact form submit), and instead of running your own PHP or Java rules on the incoming data, simply package and hand the data off to your server-side JavaScript validation routine.</p>
<p>If you get a &#8220;true&#8221; back, the data validation passed, and your application can continue as necessary. If &#8220;false&#8221; (or some other specific error messaging, if you prefer), then immediately respond back to the request with the error and don&#8217;t let the application continue.</p>
<p>I&#8217;d recommend to start off with you pick one application server touch-point, and even just one field in that inbound data, and ferry only that off to your server-side JavaScript validation. Do you see how much simpler and easier that stripped down approach is compared to a wide-spread complete re-architecture?</p>
<p>As you get comfortable with this approach, and you feel ready, you can extend your data validation to encompass more and more of your inbound data, in more and more of the application&#8217;s server touch-points, until you have all your data validation tasks written in DRY and maintainable JavaScript.</p>
<h4>The rabbit hole</h4>
<p>Data validation is only one of the dozen or so tasks that the &#8220;middle-end&#8221; entails. Your next step might be to start tackling DRY approaches to templating. Again, you should go little-by-little into that world.</p>
<p>Regardless of how you proceed, I hope it&#8217;s clear now that I advocate a pattern rather than particular implementation details, and that I advocate little baby steps along the path, rather than complex and comprehensive re-writes. <em>That</em> I believe is the right path to beginning your middle-end.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/2010/07/how-to-begin-your-middle-end/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What exactly is the &#8220;middle-end&#8221;?</title>
		<link>http://blog.getify.com/2010/07/what-exactly-is-the-middle-end/</link>
		<comments>http://blog.getify.com/2010/07/what-exactly-is-the-middle-end/#comments</comments>
		<pubDate>Thu, 08 Jul 2010 16:50:09 +0000</pubDate>
		<dc:creator>getify</dc:creator>
				<category><![CDATA[UI Architecture]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[middle-end]]></category>
		<category><![CDATA[ui]]></category>

		<guid isPermaLink="false">http://blog.getify.com/?p=425</guid>
		<description><![CDATA[Those who follow me on twitter or have heard me speaking at tech conferences this year have heard me repeatedly clamoring on about something I call the &#8220;middle-end&#8221;, or alternately, &#8220;UI Architecture&#8221;. In fact, I just finished up a 3-part article series for JSMag on &#8220;The Rise of the Middle-End&#8221;. If you want some real [...]]]></description>
			<content:encoded><![CDATA[<p>Those who follow me on <a href="http://twitter.com/getify">twitter</a> or have heard me <a href="http://slideshare.net/shadedecho">speaking at tech conferences</a> this year have heard me repeatedly clamoring on about something I call the &#8220;middle-end&#8221;, or alternately, &#8220;UI Architecture&#8221;. In fact, I just finished up a 3-part article series for <a href="http://jsmag.com">JSMag</a> on &#8220;The Rise of the Middle-End&#8221;. If you want some real meaty discussion of this topic and even code related to it, I encourage you highly to go get a subscription, or at least buy the May/June/July issues for this series.</p>
<p>But for the rest of you, I felt it was time that I distill the topic down into a very short and simple explanation, defining the topic as I see it. This post then will be the foundation for several more to come where I describe practical implementation details for the &#8220;middle-end&#8221; in web applications.</p>
<h4>Appetizer</h4>
<p>Let&#8217;s jump right in. What sits between the front-end of a web application and the back-end of an application? The &#8220;middle-end&#8221;, naturally! What&#8217;s responsible for packaging up all pieces of the UI and delivering them efficiently to the client, and then facilitating two-way communication between server and client? The &#8220;middle-end&#8221; UI Architecture. Sure, &#8220;middle-end&#8221; is sort of a contrived term to describe a concept that&#8217;s been around a lot longer than the term itself. But &#8220;middleware&#8221; is a bit more common, and describes attempts to address &#8220;middle-end&#8221; needs, so that shouldn&#8217;t be too foreign to you.</p>
<p>&#8220;I don&#8217;t think I have a middle-end in my web application.&#8221; Oh yes, you do. Trust me, you do. Every single web-application on the planet has a middle-end, whether it is well-defined and visible, or muddled and hidden. The question is not &#8220;Do I have a middle-end?&#8221; &#8212; the question is &#8220;where <em>is</em> my middle-end, and do I control it?&#8221;</p>
<p>To better answer that question, let&#8217;s get very specific about what parts of the application and stack are part of the middle-end. First, how do <em>I</em> qualify some task as either part of, or not part of, the &#8220;middle-end&#8221;?</p>
<ol>
<li>if the task can (and is commonly) done, or at least is useful in, both the front-end and the back-end of an application
<ul>
<li>Templating (static and dynamic)</li>
<li>Data Validation (form field rules, etc)</li>
<li>Data Formatting (internationalization, encoding/entities, escaping, etc)</li>
</ul>
</li>
<li>if the task is directly related to supporting or facilitating the front-end, or adapting the front-end and back-end
<ul>
<li>URL Routing (deciding which controllers handle which actions, etc)</li>
<li>Header management (request &#038; response)</li>
<li>Cookies, Sessions</li>
<li>Ajax data transport (receiving, transmitting)</li>
<li>Caching (server-side)</li>
<li>Packaging (file concatenation, minification, etc)</li>
</ul>
</li>
</ol>
<p>I could go into every one of these in detail, but that would take far too long for one post. However, if a task is a candidate (and often duplicated in) both the front-end and the back-end, it should be an obvious fit to label that task a middle-end task. In fact, it&#8217;s even better if the exact same middle-end code for a certain task can be reused in both front-end and back-end contexts (more on that in a later post).</p>
<p>Similarly, if a task is specifically dedicated to helping transition between front-end and back-end (and vice versa) or to service the nitty-gritty details of supporting the front-end, it also makes sense to call this &#8220;middle-end&#8221;.</p>
<h4>Just Fluff</h4>
<p>It&#8217;s tempting to think that since all web applications have most or all of these tasks built into the guts of the framework in one form or another, calling them out and giving them a specific name and definition is kind of unnecessary and just &#8220;trying to hard.&#8221; </p>
<p>To that, I respond: only by calling these tasks out and defining them and talking about how they are implemented can we ever truly hope to control them enough to optimize or scale or improve. Just because they&#8217;ve always been done in the underbelly of our application stack without us ever thinking about them doesn&#8217;t make that the right or most successful approach. Maybe it&#8217;s time to re-think them a little bit?</p>
<p>If you&#8217;re simply content with letting your one platform-of-choice make all these decisions for you, and handle all these tasks without you knowing or caring, then fine. Enjoy your blissful existence. Move along, nothing more to see here.</p>
<h4>More Meat</h4>
<p>The dirty secret of web performance optimization is this: while almost all of web performance optimization focuses on making the front-end more efficient and user-experience-friendly, most of the tasks you need to perform to optimize the front-end actually require some (or a lot!) of control over the &#8220;middle-end&#8221;.</p>
<p>For example, if you want to optimize the page-load performance of a page by addressing resource loading, you may right away think: &#8220;well, I just need something to combine my files together to reduce HTTP requests.&#8221; And if you happen to work in an environment where build-processes are already the norm, adding in such a task is probably not overly tedious.</p>
<p>But what if you&#8217;re in some custom-built CMS on top of PHP? What if resource references (images, scripts, CSS) are strewn about your front-end templates/code haphazardly? What then will you do? Probably your only choice at this point is manual labor to go through and change everything. And what you&#8217;ll probably be doing is inserting some sort of solution for this task into your application. </p>
<p>YES! That&#8217;s textbook middle-end work. To the extent that <em>you</em>, the front-end guy, have control over such code, this won&#8217;t be that bad. But to the extent you have to coordinate your efforts with a team of back-end developers who &#8220;own&#8221; the PHP and who don&#8217;t care as much about front-end optimization, you&#8217;re in for a less-than-fun ride.</p>
<h4>Spaghetti for dinner?</h4>
<p>Performance optimization isn&#8217;t the only motivating factor for going toward a more well-defined middle-end. Another dirty little secret, this time about popular architecture patterns like MVC, is this: by far the most common implementations of such ideas are (at best) flawed in that they leak coding implementation details between the M, the V, and the C.</p>
<p>For example, this V-view code:</p>
<pre style="background-color:#ddd;">
&lt;ol class="action_menu">
   &lt;?php if ($User->IsLoggedIn() &#038;&#038; $User->CanPublish()
                 &#038;&#038; $User->Articles->count() < $App->max_articles) { ?>
      &lt;li>&lt;a href="/publish">Publish New Article&lt;/a>&lt;/li>
   &lt;?php } ?>
   ...
&lt;/ol>
</pre>
<p>Even though we have what appears to be a decently well architected object-oriented M-model at our disposal, it&#8217;s scarily common, easy, and tempting to use the M-model inside our V-view in such a way that constitutes &#8220;business logic&#8221; (the stuff that&#8217;s supposed to only exist in our C-controller).</p>
<p>I won&#8217;t harp on this topic too much, as I&#8217;m sure there are a million different opinions out there as to whether this is good, bad, or irrelevant. There&#8217;s also probably a million other variations in other platforms where people think they&#8217;ve more or less addressed these issues. Let me just say this: If you have function/method calls, and combinatorial/boolean logic, in your V-view&#8230; you&#8217;re <em>probably</em> doing it <em>wrong</em>.</p>
<h4>Where&#8217;s Dessert?</h4>
<p>But how would a more well-defined &#8220;middle-end&#8221; help with this? The answer is quite complex and I don&#8217;t have space or the inclination to address it completely in this post. But the short answer is that I propose an alternate architectural pattern to MVC that I call CVC (Client-View-Controller) which is more UI-centric (whereas MVC was clearly conceived by a back-end architect!).</p>
<p>CVC has lots of important details to it, but the main one I want to call attention to here is this: <em>proper</em> implementation <strong>insists</strong> that there be a <strong>strict</strong> and <strong>unwavering</strong> separation between application code (controllers or models) and presentation (view templates). This separation is achieved primarily by stripping down the M-model to something more like bare D-data before it is sent into the V-view.</p>
<p>With CVC, you can still maintain whatever kind of platform or environment you currently have, for your back-end application. The only required change is that you take out <strong>all</strong> code that is related to presentation in any form, and leave that to the strictly separate and well-defined &#8220;middle-end&#8221;. All your application back-end needs to do is serialize data to hand off to the middle-end. So, it becomes a headless, API-driven, &#8220;black box&#8221;. </p>
<p>And your middle-end code is now free to take data and format it for presentation in V-view templating completely agnostic of how the data was constructed by the business logic of the back-end.</p>
<p><img src="http://getiblog.2static.it/wp-content/uploads/2010/07/cvc-ui.png" alt="CVC UI Architecture" title="CVC UI Architecture" width="575" height="429" class="aligncenter size-full wp-image-440" /></p>
<p>The biggest gain, in terms of developer processes, from this middle-end rethinking will be more maintainable and robust code. Front-end developers will not have to worry about changing all their templates when the back-end developers make a change to the signature of the M-model. Back-end developers will not have to make exceptions in their code for when front-end developers want to, for various reasons, transfer data to/from the client as an array instead of a keyed hash.</p>
<h4>Take-out food</h4>
<p>If you don&#8217;t get anything else from this post, get this: <strong>the front-end and the back-end naturally and automatically shape up more orderly when you insert a well-defined &#8220;middle-end&#8221; in between.</strong> Will it take some re-thinking and a little bit of refactoring? Yes. Do you have to ditch everything you know about your application infrastructure and start over from scratch? <strong>Absolutely not.</strong></p>
<p>Bottom line: your application already has a &#8220;middle-end&#8221;. You probably just don&#8217;t know it&#8217;s there or never think about it. Isn&#8217;t it about time you do?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/2010/07/what-exactly-is-the-middle-end/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Why I don&#8217;t like HAML</title>
		<link>http://blog.getify.com/2010/02/why-i-dont-like-haml/</link>
		<comments>http://blog.getify.com/2010/02/why-i-dont-like-haml/#comments</comments>
		<pubDate>Thu, 04 Feb 2010 19:38:52 +0000</pubDate>
		<dc:creator>getify</dc:creator>
				<category><![CDATA[Misc]]></category>
		<category><![CDATA[UI Architecture]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[template]]></category>
		<category><![CDATA[templating]]></category>
		<category><![CDATA[ui]]></category>

		<guid isPermaLink="false">http://blog.getify.com/?p=168</guid>
		<description><![CDATA[Disclaimer
Before I begin, let me share my personal mantra: &#8220;everyone is entitled to their own (wrong) opinions.&#8221; This includes me. This post is purely opinion. It&#8217;s an editorial. It means nothing unless you care what my opinion is. If you&#8217;re easily offended, or if you just love HAML, or if you&#8217;re a closed minded bigot, [...]]]></description>
			<content:encoded><![CDATA[<h2>Disclaimer</h2>
<p>Before I begin, let me share my personal mantra: &#8220;everyone is entitled to their own (wrong) opinions.&#8221; This includes me. This post is purely opinion. It&#8217;s an editorial. It means nothing unless you care what my opinion is. If you&#8217;re easily offended, or if you just love HAML, or if you&#8217;re a closed minded bigot, or whatever, just move on. Really. </p>
<p>I really don&#8217;t care what your opinion is on this topic, I just want to express mine, for the record, for posterity sake. And I&#8217;m not trying to convince anyone to use or <strong>not use</strong> HAML. I simply want to state the things I dislike about it. </p>
<p>I&#8217;m a fundamentalist, and I prefer simplicity in almost all cases. My bias toward performance, customization, control, optimization, and other such ethics should be evident from this blog already. This automatically makes me suspicious of &#8220;all-in-one&#8221; anythings. I&#8217;m the anti-framework guy. I&#8217;m the anti-platform guy. I&#8217;m the guy who wants the bare minimum in place to get my task done effectively. And I believe that in doing so, with as few layers of abstraction (and processing) as feasible and possible, you will end up with more performant code. </p>
<p>But this doesn&#8217;t <em>have</em> to come at the price of less maintainable code. It&#8217;s just that for years, the development community has strived for more maintainable code, and the only answer we&#8217;ve ever figured out collectively is to put higher and higher levels of abstractions on things. </p>
<p>Some abstraction is good and smart (<a href="http://twitter.com/brandonaaron/status/8596115868">we don&#8217;t write 0&#8217;s and 1&#8217;s</a>, thanks @<a href="http://twitter.com/brandonaaron">brandonaaron</a>!!), but to the level that a lot of people take it, I liken it to using a pictures-only menu at a fast food restaurant. No offense to the foreign or illiterate, who I&#8217;m sure that is helpful to, but if you <em>can</em> read, you <em>should</em>. Pointing to the picture of a hamburger, then the picture of a ketchup bottle, then&#8230; this is inferior to just saying &#8220;Hamburger with ketchup&#8221;, if you <em>can</em> say that. Just my opinion.</p>
<p>Anyway, my goal with this post is to identify the fundamental approaches (not just nit-picking) of HAML that I dislike. Actually, to be fair, HAML is not the problem itself, HAML is just a symptom of the larger problem, convenient to help me illustrate some thoughts on templating as a discipline.</p>
<p>I&#8217;ll continue the discourse in subsequent post(s) with other opinions, and even some suggestions I have for solutions. Hopefully you&#8217;ll stick around and get something out of it. If not, that&#8217;s fine, too.</p>
<h2>Brief overview of HAML</h2>
<p>For those who aren&#8217;t aware, <a href="http://haml-lang.com/">HAML</a> is a templating language, apparently most closely associated with Ruby, that uses some &#8220;shorthand&#8221; to express HTML structures. It&#8217;s important to note that it&#8217;s more involved than a simple shorthand such as Wiki/<a href="http://en.wikipedia.org/wiki/Markdown">markdown</a>, as it appears aimed to be a full-fledged templating engine.</p>
<p>As it includes a templating &#8220;language&#8221; (a <a href="http://en.wikipedia.org/wiki/Domain-specific_language">DSL</a>, technically), it has the usual suspects, including variable replacement, logical selection operators, &#8220;sub-template&#8221; includes, comments, etc. It also allows/includes Ruby (or Ruby-like, not quite sure) syntax for more complicated logic, such as function definitions, looping, math operations, etc.</p>
<p>Let&#8217;s identify first the most important characteristics of HAML (at least, those relevant to my points):</p>
<ul>
<li>HAML uses CSS-like shorthand to reverse-declare HTML tags. (HAML assumes a &#8220;&lt;div>&#8221; tag type unless otherwise specified).
<p>Example:</p>
<pre style="background-color:#ddd;">
#mydiv
    %span.message
        Hello World
</pre>
<p>Would result in:</p>
<pre style="background-color:#ddd;">
&lt;div id="mydiv">
    &lt;span class="message">Hello World&lt;/span>
&lt;/div>
</pre>
<p>It&#8217;s easy to see how in this respect, the &#8220;shorthand&#8221; for the resultant HTML seems easier to write/maintain.
</li>
<li>HAML uses whitespace indentation nesting to signal scope of tag blocks. This is <strong>critical</strong> for HAML being able to know where a block ends without needing closing tags, a big part of the &#8220;shorthand&#8221; being achieved.
<pre style="background-color:#ddd;">
#mydiv
    %ol#mylist
        %li.myitem
            Hello
        %li.myitem
            World
</pre>
<p>Results in:</p>
<pre style="background-color:#ddd;">
&lt;div id="mydiv">
    &lt;ol id="mylist">
        &lt;li class="myitem">Hello&lt;/li>
        &lt;li class="myitem">World&lt;/li>
    &lt;/ol>
&lt;/div>
</pre>
<p>Again, clearly the &#8220;shorthand&#8221; syntax has some appealing aspects, so far. If you like/don&#8217;t mind &#8220;whitespace sensitive languages&#8221; like Python and VB, you&#8217;ll be ok with using indentation in place of closing tags.
</li>
<li>
For more complex tasks, like math operations, dropping in variable replacements, calling functions, executing logic, etc, HAML allows you to use an = sign to signal a line of Ruby code to be executed in the context of the template parsing, with the output being added to the template at that point. (You use a &#8211; to indicate Ruby that should execute but which returns no desired output to include in the template).</p>
<p>Example:</p>
<pre style="background-color:#ddd;">
- (42...45).each do |i|
    %p= i
</pre>
<p>Results in:</p>
<pre style="background-color:#ddd;">
&lt;p>42&lt;/p>
&lt;p>43&lt;/p>
&lt;p>44&lt;/p>
&lt;p>45&lt;/p>
</pre>
<p>There are other variations of how to include/execute Ruby code as well. The point is, HAML tries to make it pretty easy for you to execute logic in your template, as long as that logic is Ruby. Also, they make one little buried warning in the documentation about encouraging you not to run Ruby logic which <em>should be</em> in the Controller. It&#8217;s not enforced in anyway, but I guess if you read <strong>and</strong> obey, that&#8217;s helpful.
</li>
</ul>
<p>There&#8217;s certainly more (<a href="http://haml-lang.com/docs/yardoc/file.HAML_REFERENCE.html">a lot more</a>, in fact) to HAML than this short list. I&#8217;m not writing a book on HAML (or anti-HAML) here, so I&#8217;m just trying to keep it to a minimum. But let&#8217;s just suffice it to say, there&#8217;s a few dozen different syntax rules, tag types, practices, etc that are required to use a HAML template for a non-trivial task like building a full dynamic web app page. Also, you&#8217;re going to have to know Ruby to get much more than simple &#8220;shorthand&#8221; HTML out of the deal.</p>
<h2>My opinions</h2>
<p>I&#8217;m going to assume if you&#8217;re still reading this blog post at this point, you&#8217;re here because you a) care about my opinions, or b) care enough to want to discredit my opinions. If you&#8217;re in group (a), read on. If you&#8217;re in group (b)&#8230; well&#8230; refer back to the first sentence of the post about my personal mantra.</p>
<h4>Whitspace/indentation scoping</h4>
<p>So, first off, I hate, absolutely detest, cannot stand, whitespace-sensitive languages. I cannot think of hardly anything in programming paradigms that irks me more than having to try and determine a set of logic context and having to count the number of indented columns (if they are spaces and not tabs, for instance) to figure out which blocks go together. This is doubly true if you choose to use like 1 or 2 space indentation, which I&#8217;ve seen at a couple of my previous jobs. </p>
<p>I suppose if you used 10 spaces for each indentation mark, it might make things obvious enough, but then you&#8217;re defeating the purpose of trying to use shorthand if you have to add and manage a bunch of extra characters to help make scope identifiable.</p>
<p>This brings up my counter opinion: languages like C and JavaScript use just 2 characters to identify blocks; the &#8220;{&#8221; and the &#8220;}&#8221;. This also makes it easier for code editors to give you helpful hints like highlighting closing and opening &#8220;tags&#8221;, and helping you know if you have unbalanced/unclosed elements, etc. I like this in JavaScript and C styled languages, so it natually should extend that I like this in HTML.</p>
<h4>I don&#8217;t like complications</h4>
<p>The above examples look really nice, and are probably the sweet spot for how HAML shines. But if you read <a href="http://haml-lang.com/docs/yardoc/file.HAML_REFERENCE.html">the long form documentation</a>, you&#8217;ll quickly see that there are lots of other complicating scenarios which you must learn to deal with. Indeed, HAML is not just shorthand convenient HTML, it&#8217;s a DSL with sytnax and rules and exceptions and gotchas all its own.</p>
<p>For instance, consider the case of wanting to add some attributes to a tag. Here&#8217;s an example from the documentation of the proper way to do it with HAML.</p>
<p>Say you want this HTML:</p>
<pre style="background-color:#ddd;">
&lt;sandwich bread='whole wheat' delicious='true' filling='peanut butter and jelly' />
</pre>
<p>Just use this &#8220;little&#8221; snippet of goodness (makes me hungry just reading it):</p>
<pre style="background-color:#ddd;">
def hash1
    {:bread => 'white', :filling => 'peanut butter and jelly'}
end
def hash2
    {:bread => 'whole wheat'}
end
%sandwich{hash1, hash2, :delicious => true}/
</pre>
<p>Uhhh, wait a second. I thought HAML was supposed to be shorter and simpler. I dunno about you, but this does not appear shorter <strong>or</strong> simpler to me. Maybe that&#8217;s just because I&#8217;m not a Ruby developer. Or maybe that&#8217;s just because at the point where I want to write HTML, I want to write stuff that looks like&#8230; HTML.</p>
<p>Moreover, if I have someone whose specialty is HTML and not Ruby, I <strong>really</strong> don&#8217;t want them trying to write such Ruby code. But maybe that&#8217;s just me.</p>
<p><strong>Update 4/27/2010</strong>: John commented to suggest a shorthand for the above in HAML:</p>
<pre style="background-color:#ddd;">
%sandwich{:bread => 'whole wheat', :filling => 'peanut butter and jelly',
:delicious => true}/
</pre>
<p>Certainly this is better than the above (although still inferior to HTML itself IMHO), which by the way came from the official HAML documentation (not me that made that up). I&#8217;m sure they did that to demonstrate how you can override properties with subsequent hashes, etc. But as I said in response to John, the fact that the more complicated form is what&#8217;s found in the HAML documentation will probably lead to more &#8220;newbies&#8221; like me thinking this is the standard way to do HAML. I have the same problem with the thousands of .NET MVC tutorials on the first few pages of Google SERP&#8217;s that tell people the completely wrong way to pass data from the Model to your View. If you document the bad practices enough, the bad practices will become the de facto standard. This is bad. Very bad.</p>
<h4>When writing HTML, I should be writing&#8230; HTML</h4>
<p>Perhaps I should state rather than just imply a bias I have here: if I&#8217;m in the mode of doing front-end (HTML) development (&#8217;cause I know a lot of us wear many different hats from front-end dev to back-end dev in our jobs), I want to think in HTML (not something else) at that point in time. Just like when doing back-end app development, or when building out database schemas, I darn sure don&#8217;t want to care (at that moment) about the eccentricities of cross-browser CSS and box-model support.</p>
<p>I think this kind of role separation (and thus skill separation) makes my job easier. It makes is clearer what I&#8217;m doing at any given point, instead of trying to blur syntactical lines between various technologies in the name of convenience.</p>
<p>I just find I work more effectively when I do only what is necessary for a given task at any one time.</p>
<h4>Templates and Code Logic should not mix</h4>
<p>I feel like this point is almost so self-obvious, I&#8217;m boring you by mentioning it. But yet time after time I see various platforms and frameworks (everything from .NET to Java to PHP to RoR to HAML to everything else in between) making exceptions to these rules, in whole or in part, and allowing (or even encouraging!) you to add some host language logic directly inside your templates.</p>
<p>I guess the logic follows that if you&#8217;re a Ruby developer, and you&#8217;re also tasked with doing front-end (HTML) development, you won&#8217;t mind mixing the two in your mind, using Ruby code logic to assemble your templates and data.</p>
<p>Well, that&#8217;s great until you hire a rock-star HTML/CSS guy to make templates who has zero knowledge of Ruby. I suppose you just hand him a Ruby book and say, &#8220;good luck.&#8221;? Or what about if you decide at some point to change the back-end platform technology you&#8217;re using from Ruby to say Scala or Erlang or PHP or whatever. What becomes of all your templates? Do you keep the Ruby based stuff, or do you ditch them entirely and re-write all your presentation layer as well?</p>
<p>And, btw, how does your development team make decisions effectively about what&#8217;s ok to be Ruby embedded in your templates, and what must be in the controllers? How do you train new developers to your team how to effectively make these decisions quickly right along side all your seasoned developers who&#8217;ve stubbed their toes on those topics for years? How do you decide, philosophically, if logic related to formatting (say a date or currency) is logic that should belong in the templates or in the controllers?</p>
<p>You see, in my opinion, all these questions are harder <strong>because</strong> you&#8217;re using a system that&#8217;s more flexible, more powerful, more complicated than it <em>needs to be</em> or <em>should be</em>. </p>
<p>Just because I <em>can</em> hammer a nail in with a sledge hammer doesn&#8217;t mean that&#8217;s the most effective tool for the job. If I have a little hammer suitable for the task, I think it&#8217;ll be more accurate and efficient to use it than the big sledge hammer. And that&#8217;ll also be true when I hand off the task of nailing things in to a new person who&#8217;s never used the sledge hammer before.</p>
<p><strong>Point:</strong> You don&#8217;t need the power of Ruby to construct templates. If you do, you&#8217;re doing templating wrong &#8212; again, in my opinion. Templating only needs a few simple constructs to be effective. Anything beyond that <em>should be</em> in your Controllers. At least, that&#8217;s what we were all taught in our CS classes when we learned about the proper Object-Oriented approach to MVC and we had it drilled into us that the &#8220;M&#8221;, the &#8220;V&#8221;, and the &#8220;C&#8221; should be separate. How quickly we abandon &#8220;separation&#8221; when it becomes too convenient in the heat of the moment.</p>
<p>I love <a href="http://twitter.com/KentBeck/status/8637230540">this quote I just read</a> on twitter: &#8220;good programmers appreciate the features you put in. expert programmers appreciate the features you left out.&#8221; (via <a href="http://twitter.com/KentBeck">KentBeck</a>)<br />
<h4>Portability</h4>
<p>I&#8217;m also not a fan of having to use more than one templating system. By this, I mean, it is a reality of <strong>most</strong> (even mildly) complex web apps that there are two classes of templating: build-time (on the server) and dynamic (run-time, in the browser, with user input). Of course, various web apps have a different mix, and if you&#8217;re in the small class that is entirely one or the other and always will be, just skip over this point.</p>
<p>However, for the rest of us, almost nothing upsets me more than having to repeat myself. We&#8217;ve all heard DRY (don&#8217;t repeat yourself), but I don&#8217;t just quote that as a nice-to-have, I try hard to live by it in my development career. I am not 100% sure, but I&#8217;d hazard a good guess that it&#8217;s impossible to use the exact same templates (with Ruby logic and all) in both a server environment and a client environment. Moreover, even if there is a port (to JavaScript) of the HAML interpreter that could run in the browser (with alternate templates of course), this is of course two different separate copies of a templating engine that must be independently maintained.</p>
<p>A fundamental &#8220;law&#8221; in Computer Science is that anytime there is more than one copy of something, one copy is always wrong. That&#8217;s where DRY was born from. And it goes for tools as well as content.</p>
<p>You may be saying to yourself, &#8220;wait, that&#8217;s not possible with any templating engine.&#8221; Ahh, but it is! Stay tuned, in a (soon) future blog post here I&#8217;ll be talking about a templating engine I&#8217;ve built which can do just that.</p>
<p>You know what technologies <strong>can and do</strong> run in both contexts? JavaScript and HTML. Anything other than that, and you&#8217;ve almost certainly failed this point. Game over.</p>
<h4>One more thing</h4>
<p>One last point of contention: I am unable to confirm how HAML handles &#8220;compilation&#8221; of templates. If it does so on-the-fly, every time, at run time (since it also has to execute Ruby code to drop in data), then this is more inefficient to convert from shorthand code to raw HTML each time.</p>
<p>If however it has some sort of two-pass compilation, where at build time you compile the shorthand HAML to raw HTML, and then at run-time you execute the embedded Ruby to drop in data, then this is probably a better approach efficiency wise. </p>
<p>Still, the point remains, that type of technique is important for performance, and it&#8217;s not very common amongst most templating solutions.</p>
<h2>Enough already</h2>
<p>OK, that&#8217;s enough ranting for one post. Again, the purpose here was to lay out what I don&#8217;t like about HAML. The underyling frustrations however are not specific to HAML but are true of many, many templating solutions. So up coming will be posts where I try to be more constructive and offer some solutions. Hopefully you&#8217;ll find this dialogue helpful. That is of course if you haven&#8217;t already written me off as being a crazy, eccentric, opinionated technology bigot.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/2010/02/why-i-dont-like-haml/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 @ 2010-09-07 21:08:38 -->