<?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; JavaScript</title>
	<atom:link href="http://blog.getify.com/category/ui-arch/javascript-ui-arch/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>JSConf 2010 &#8211; getify on middle-end/ui architecture</title>
		<link>http://blog.getify.com/2010/08/jsconf-2010-getify-on-middle-endui-architecture/</link>
		<comments>http://blog.getify.com/2010/08/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>
]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/2010/08/jsconf-2010-getify-on-middle-endui-architecture/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Node.js: The end of the middle?</title>
		<link>http://blog.getify.com/2010/07/node-js-the-end-of-the-middle/</link>
		<comments>http://blog.getify.com/2010/07/node-js-the-end-of-the-middle/#comments</comments>
		<pubDate>Sun, 18 Jul 2010 19:30:29 +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]]></category>

		<guid isPermaLink="false">http://blog.getify.com/?p=480</guid>
		<description><![CDATA[If you haven&#8217;t yet read my ode to why Node.js is awesome, stop and go do so now. It should be no surprise by now that I am giddy like a school girl over the idea of using server-side JavaScript to revolutionize the web application stack. And perhaps no other project has captured more of [...]]]></description>
			<content:encoded><![CDATA[<p>If you haven&#8217;t yet read my <a href="http://blog.getify.com/2010/07/why-node-js-rocks-the-middle-end">ode to why Node.js is awesome</a>, stop and go do so now. It should be no surprise by now that I am giddy like a school girl over the idea of using server-side JavaScript to revolutionize the web application stack. And perhaps no other project has captured more of the imagination and zealotry from the JavaScript developer community as <a href="http://nodejs.org">Node.js</a> has over the last 6-9 months. It&#8217;s undeniable that Node.js will continue to be one of the most important players in this emerging &#8220;market&#8221;.</p>
<p>But silver-bullet or the second-coming of the web? I&#8217;m not so sure Node.js can quite claim that status. Here, we&#8217;ll investigate the counter-point to Node.js, especially as it relates to practical usage in the middle-end. Raining on the parade may not be fun, but if we&#8217;re gonna gulp down the delicious Node.js grape kool-aid, we&#8217;re also gonna have to stomach a healthy amount of that ick-tasting Node.js cough syrup (that&#8217;s right, I just mixed 3 metaphors in one sentence!). We owe this topic some intellectual honesty and debate.</p>
<h4>Brad Pitt in &#8220;Interview with a devil&#8221;</h4>
<p>I want to (re)introduce you to a good friend of mine. He&#8217;s exceedingly well known, and I&#8217;m sure you&#8217;ve met him many times before. He&#8217;s not a popular guy by any means &#8212; probably more infamous than famous &#8212; but he can be very assistive in times when the hype of something <em>new</em> clouds our judgement of the things we already <em>knew</em> well.</p>
<p><span class="me"><strong>Me:</strong> Devil&#8217;s Advocate (&#8220;DA&#8221;), welcome to the show. I&#8217;m glad you could join us for this discussion today.</span></p>
<p><strong>DA:</strong> Thank you for inviting me over for some tea and a lively discussion. You know how much I enjoy calmly reminding people of reality, and in the process spoiling a lot of their fun.</p>
<p><span class="me"><strong>Me:</strong> DA, are you saying you <em>like</em> being the least popular guy at the party? A lot of people think you are a Contrarian&#8230; that you just like to disagree for the sake of disagreement, and that you don&#8217;t really <em>help</em> the discourse very much. What do you think of that characterization?</span></p>
<p><strong>DA:</strong> Well, that&#8217;s true that most people probably think of me that way. But that&#8217;s ok, I am secure in my manhood and it doesn&#8217;t bother me that much. I&#8217;m used to intellectual rejection. I mean, look at how hard I&#8217;ve been working to try and wake people up to Apple&#8217;s antics with the iPhone 4 antenna, and yet the masses still cling to Jobs&#8217; every word like he&#8217;s a prophet or&#8230;</p>
<p><span class="me"><strong>Me:</strong> Ok, DA. Let&#8217;s not get off on that tangent here. That <em>is</em> a fun topic, but we&#8217;ve got more important things to deal with today.</span></p>
<p><strong>DA:</strong> Sorry, sometimes I just get carried away. But I do think my methods are helpful in encouraging people to question certain assumptions and make sure that all sides of a topic have been examined thoroughly.</p>
<h4>Hello World</h4>
<p><span class="me"><strong>Me:</strong> That&#8217;s good. Let&#8217;s jump right in. I know you read my previous post where I gushed over how awesome Node.js is and where I explored how it might fit with the middle-end concepts I&#8217;m advocating for.</span></p>
<p><strong>DA:</strong> Of course. I wrote that little editorial sidebar as a preview of our discussion today.</p>
<p><span class="me"><strong>Me:</strong> Right. So, tell the readers, what do you think of Node.js?</span></p>
<p><strong>DA:</strong> It&#8217;s awesome. Really it is. But it&#8217;s awesome for a specific set of tasks and for a specific kind of scenario. We have to be careful to remember that even though it&#8217;s very exciting for developers to jump on board and start experimenting with a new implementation like Node.js, that doesn&#8217;t mean in any way that it&#8217;s going to work for everyone.</p>
<p><span class="me"><strong>Me:</strong> Obviously not, no one technology is ever right for everyone. I don&#8217;t think anyone is suggesting that. Seems like you&#8217;re just chewing on the soggy cheerios.</span></p>
<p><strong>DA:</strong> No, it&#8217;s more than that. I&#8217;m actually trying to help people realize <em>exactly</em> what Node.js <em>is</em> and <em>is not</em>, so that we can have productive discussions not only about Node.js and its uses, but <em>also</em> about other alternatives for the rest of the crowd.</p>
<p><span class="me"><strong>Me:</strong> Don&#8217;t you think it&#8217;s just too early to be judging what Node.js can and cannot do? I mean, isn&#8217;t it possible that it&#8217;ll grow to be useful in more parts of the stack as time goes on?</span></p>
<p><strong>DA:</strong> It&#8217;s entirely possible and likely that Node.js will continue to grow in popularity, and more and more waves of developers will find innovative uses for it. But I don&#8217;t necessarily think that means it will ever win over the minds of conservative, established and slow-to-change development teams &#8212; and especially their bosses and IT support staff.</p>
<p><span class="me"><strong>Me:</strong> Why not?</span></p>
<p><strong>DA:</strong> It&#8217;s purely pragmatism, I feel. I&#8217;m considering the <em>majority</em> of the web application universe to be of the sort that is not naturally bleeding-edge (even if the bleeding edge is awesome) and often follows well behind the curve, and sometimes never follows at all. I&#8217;m thinking of the millions of PHP shops, and the Java shops, and lord knows the .NET shops&#8230; all of them out there, chugging along in their own little world. That world is not likely to be &#8220;rocked&#8221; (as you called it) by Node.js or even server-side JavaScript.</p>
<p>The payoff for them re-writing most or all of their current code base (whatever language it is) into server-side JavaScript would have to be epic and enormous, almost beyond adequate description in words, to convince them it&#8217;s worth all the time, money, and <em>risk</em> such a venture would entail.</p>
<h4>Change you can believe in?</h4>
<p><span class="me"><strong>Me:</strong> OK, fair enough, a lot of them might be resistant to change. But aren&#8217;t all new technologies up against that same battle at first? The ones that eventually prevail do so despite the nay-sayers (like you) from the early days.</span></p>
<p><strong>DA:</strong> On the surface, you&#8217;re correct. But again, I&#8217;m talking about something much deeper and more fundamental than just: will the masses ever accept server-side JavaScript? </p>
<p>In fact, I think that&#8217;s really <em>your</em> biggest question to answer as you try and convince people to embrace the middle-end with server-side JavaScript as the driving technology. Yes, the middle-end as a concept doesn&#8217;t require JavaScript, but the biggest payoffs in the middle-end come if people will accept server-side JavaScript into the stack. You&#8217;ve got a big uphill battle even trying to convince people that a little tiny piece of the stack can be done adequately with server-side JavaScript.</p>
<p><span class="me"><strong>Me:</strong> Thank you for reminding me just how challenging this is.</span></p>
<p><strong>DA:</strong> My bigger point is, Node.js at its fullest is much broader than I think most people realize. I think it represents a paradigm shift, not just the introduction of an existing technology into a new environment. </p>
<p>I think I&#8217;d liken this concept to trying to convince a company that makes desktop video-editing software that the new age will be their software web/cloud-based and mobile. Noone would argue that the mobile and cloud movements are huge and clearly represent the future. But the desktop application company is probably still likely to adhere to their core competency and continue to serve and rely on the paradigm of desktop application and hardware.</p>
<p>And they may rightly argue that the payoff for being able to take even part of their awesome video-editing functionality and stick it on a tiny screen device with 1/100th the CPU power probably doesn&#8217;t justify the efforts to try and get on the bandwagon with &#8220;everyone else&#8221;.</p>
<p><span class="me"><strong>Me:</strong> A paradigm shift? Can you elaborate?</span></p>
<p><strong>DA:</strong> Here&#8217;s what I mean: Node.js is not <em>just</em> an execution environment for server-side JavaScript. In theory, you <em>could</em> just run JavaScript on the server in an on-demand way, as needed. And I bet Node.js would be pretty decent at that task.</p>
<p>But by even thinking about Node.js in that light, you&#8217;ve drastically missed the point of what it&#8217;s trying to do. Node.js is trying to leverage the asynchronous power of JavaScript at a deeper level than on-demand application logic. Node.js is trying to <em>become</em> the network server itself, so that the server-side JavaScript you write for your application can be interpreted in a much more natural and almost native way.</p>
<p>Let&#8217;s look at this in light of some more established existing functionality. Consider a PHP web application. Now consider there&#8217;s some additional &#8220;module&#8221; for some task, like for instance doing OpenSSL encryption/decryption. There&#8217;s multiple ways your PHP code could accomplish this task. We know there&#8217;s command-line utilities (written in C and compiled to binaries) for managing OpenSSL. So, from our PHP, we can call out to those binaries by executing them as sub-processes.</p>
<p>But this isn&#8217;t necessarily the most efficient way to do things. It certainly <em>can</em> make code look less graceful and more complicated to maintain (more moving parts). Instead, we&#8217;d like it if someone could write a PHP &#8220;extension&#8221; that brings the capabilities of the OpenSSL engine natively into our PHP code. Coding against a PHP API for OpenSSL feels more natural than executing a binary sub-process, and it&#8217;s also likely to be a lot more performant.</p>
<p><span class="me"><strong>Me:</strong> That sounds about right.</span></p>
<p>I can&#8217;t speak for the designers of Node.js, but I&#8217;d venture that among their various motivations, they wanted to do something similar (but in a much broader sense) for server-side JavaScript in the web stack. They wanted to make coding <strong>your entire application in JavaScript on the server</strong> as natural and native and built-in feeling as doing any other task in the web server, including listening for requests on port 80, doing file I/O, etc.</p>
<p>You see, the different paradigm that Node.js is bringing to the table is the idea that the web server and the application become almost synonymous. I think more than anything, <em>that</em> is the truly compelling story for Node.js. I&#8217;m not saying that Node.js is the <em>first</em> to do this, but I do think that Node.js is the most radical approach in this area that we&#8217;ve seen thus far.</p>
<h4>Vive la Révolution!</h4>
<p><span class="me"><strong>Me:</strong> Ok, so that does sound pretty revolutionary. But I missed the part about how this <em>doesn&#8217;t</em> fit well with the middle-end.</span></p>
<p><strong>DA:</strong> Well, you certainly are the primary advocate for the middle-end, so I won&#8217;t try to speak for you. But, I think you and I have some parallel thoughts in mind at this point, even if you don&#8217;t realize it. <em>You</em> have a vested interest (by virtue of your efforts to call attention to the middle-end) in convincing the &#8220;world&#8221; to adopt middle-end architecture as an intentional and carefully planned layer. The more applications/teams that do so, the more you will &#8220;prove&#8221; that middle-end architecture <em>needs</em> to be its own discipline and not just an after-thought of existing platforms/frameworks.</p>
<p>I&#8217;m trying to suggest that Node.js represents a fundamental shift in how people will think about web servers and applications, not as separate functional units but as conjoined parts of the same whole. A web application no longer has to be thought of as a set of business logic code and pretty HTML that relies on a web server to send it to users. A web application is fully self-contained and capable of doing everything it needs from within itself. And it uses a consistent language (JavaScript) to do everything throughout.</p>
<p>This idea is so radical that I think most web applications and platforms and companies will have a hard time swallowing it, at least any time in the relevant future. Thus, I submit that a &#8220;middle-end&#8221; that relies on Node.js will be less palatable to the masses than a &#8220;middle-end&#8221; that is more agnostic and flexible.</p>
<p><span class="me"><strong>Me:</strong> Right, I&#8217;ve tried to make the point that the middle-end as an architectural pattern doesn&#8217;t <em>have</em> to have JavaScript on the server involved. Really, the primary reason for why server-side JavaScript offers an interesting answer to the middle-end is the idea that we can write code once and re-use it in both server and browser. No other language/technology can ubiquitously offer that.</span></p>
<p><strong>DA:</strong> Exactly. You see, Node.js represents a <em>particular</em> narrowed down implementation of the broader middle-end concept into one specific form. That form happens to be increasingly exciting to the bleeding edge of the web development community, but I foresee problems in truly convincing the establishment that both Node.js <em>and</em> the middle-end together will be right for them.</p>
<p>Take the Chrome browser for example. It&#8217;s got a huge percentage of market-share among open web developers. Along with Firefox, Chrome is quite obviously becoming a web developer&#8217;s browser of choice. But when taken in the overall context of the web, Chrome&#8217;s percentage is still pretty low. There&#8217;s an established momentum around browsers like IE and Safari, and Chrome is not likely to completely overtake them any time in the foreseeable future.</p>
<p>Node.js is an amazing piece of technology. But it&#8217;s almost <em>too</em> amazing for the middle-end. It certainly will be more radical to convince existing applications to embrace the fullness of what Node.js is than it would be to suggest, as you have many times, that a more simple, stripped down approach to server-side JavaScript is possible, and in fact warranted.</p>
<h4>Army of none</h4>
<p><span class="me"><strong>Me:</strong> Why isn&#8217;t using Node.js in a more limited fashion (like on-demand or per-request as you suggest) a valid usage of Node.js?</span></p>
<p><strong>DA:</strong> I wouldn&#8217;t call it invalid. I&#8217;d just say that it&#8217;s a lot like driving a tank down to the corner store to buy some drinks. Can it get you there? Sure. Will it get the task done? Yes. Is that an effective mode of transportation? Perhaps not.</p>
<p>Some people like to argue that because Node.js has all this amazing capability built into it, it&#8217;d be foolish to not use it for your server-side JavaScript tasks because of all the extra stuff you&#8217;d miss out on if you ever decided later you needed it. This is kind of like arguing for taking the tank for the trip down to the corner store because you want to be prepared in case an invading army of aliens attacks. &#8220;Look, I&#8217;m better prepared to fight off the bad guys in my tank than I am on my little scooter.&#8221;</p>
<p><span class="me"><strong>Me:</strong> Don&#8217;t you think that&#8217;s just a little bit of an exaggeration?</span></p>
<p><strong>DA:</strong> Well, maybe a little hyperbole there. But my point remains, Node.js is way overkill for the simple middle-end tasks at hand. If someone is trying to shoehorn using Node.js into doing simple per-request on-demand JavaScript execution (the likes of which you&#8217;ve argued for in the middle-end), they are really missing the point of Node.js. </p>
<p>To put it another way: <strong>they&#8217;re using a sledge hammer to drive in a thumbtack.</strong></p>
<p><span class="me"><strong>Me:</strong> Isn&#8217;t there something to be said for using a project like Node.js for our tasks, because at least it&#8217;s pretty well known and has a lot of active developers and a vibrant support community?</span></p>
<p><strong>DA:</strong> No question, it seems like using Node.js would be the obvious choice for this task. And <strong>perhaps</strong> a developer might be better able to convince their boss to try Node.js at first than some much less known project like your <a href="http://github.com/getify/BikechainJS">BikechainJS</a> option.</p>
<p>But in the long run, I think that <strong>using the right tools for the job always wins</strong> out in terms of efficiency and maintainability over using the more popular or hyped solutions and later on finding it&#8217;s not a good fit.</p>
<p><span class="me"><strong>Me:</strong> If one of those &#8220;established&#8221; companies <em>was</em> going to broaden their horizons, isn&#8217;t it riskier for them to venture off into the wilderness and choose an unknown project/option as compared to sticking closer to home with something more people know better?</span></p>
<p><strong>DA:</strong> It may <em>appear</em> riskier. And definitely perception is hugely important in this game. But in reality, Node.js is actually asking an existing team/platform to put more of their eggs in the server-side JavaScript basket than what you&#8217;ve argued for in the stripped-down middle-end approach. </p>
<p>Like I said earlier, Node.js is a fundamental paradigm shift. This means that companies are going to have to retool a big portion of their web stack. They&#8217;re going to have to train IT support staff on a whole new set of technologies in the web stack. They throw out their 5, 10, 15 years of experience supporting and performance tuning traditional synchronous web servers like Apache, and now they have to learn it all again with a radically different asynchronous server-side JavaScript web server. I shouldn&#8217;t have to point out what a &#8220;shock&#8221; that would probably be to most organizations.</p>
<p>And the risk doesn&#8217;t stop there. Node.js itself is ever-changing. It&#8217;s stabilizing more recently, but it&#8217;s been incredibly volatile. I&#8217;d say right now it&#8217;s like walking over a bed of molten volcano lava that only a few hours ago started cooling and hardening into volcanic rock. How much do <em>you</em> trust that an inch of cooled volcanic rock is enough to protect you (and your 800 lb elephant) from the river of lava just below the surface?</p>
<p><span class="me"><strong>Me:</strong> Doesn&#8217;t <a href="http://www.commonjs.org/">CommonJS</a> offer us hope of stability and compatibility?</span></p>
<p><strong>DA:</strong> Absolutely, it promises that. But it may be literally <em>years</em> before there&#8217;s consensus in the server-side JavaScript world on how all these API&#8217;s should really look and function. In fact, if the browser API&#8217;s have taught us anything, we may <em>never</em> fully have agreement.</p>
<p>Now, certainly the browser irregularities didn&#8217;t sideline 10&#8217;s of millions of companies from leaping into web applications, but most of them didn&#8217;t dare venture into the game until there was at least some sort of reasonable &#8220;gap fill&#8221; like any of the various JavaScript frameworks, which normalize differences across browsers and provide a stable foundation for companies to build upon.</p>
<p>So it may be awhile before CommonJS and/or some set of server-side JavaScript &#8220;frameworks&#8221; are able to secure a stable footing. If you look at Node.js right now, it represents a significant super-set of the small amount that CommonJS participants have &#8220;agreed&#8221; on. So, marrying yourself to Node.js right now is risky because it&#8217;s like marrying your web application to only FF and hoping that its rampant popularity will be enough to drive everyone else to commonality.</p>
<h4>Fatalism: a cruel mistress</h4>
<p><span class="me"><strong>Me:</strong> So can we really do <em>anything</em> with server-side JavaScript at this point, given the immaturity and instability across the board?</span></p>
<p><strong>DA:</strong> Of course! I&#8217;m not at all suggesting Node.js is bad to use because its unstable. I&#8217;m suggesting it has its places where it&#8217;s a natural fit (like in prototypes, developer experiments, and other flexibile-to-change dev environments), and then it also has places it&#8217;s not a good fit (like established teams with slow-to-change environments).</p>
<p>The same would be true of any server-side JavaScript option at this point, in my opinion. Of course there&#8217;s the obligatory &#8220;use-at-your-own-risk&#8221; label on all such things. But the smaller, more independent, and more custom your server-side JavaScript implementations are, the more likely you are to be able to adjust as the &#8220;industry&#8221; matures and changes.</p>
<p>At this point, if you were to go out and re-write your entire application in Node.js&#8217;s flavor of server-side JavaScript, you could be painting yourself in a corner if what evolves over the next few years is not in line with how Node.js is currently doing things.</p>
<p>My point is that the smaller the footprint of your server-side JavaScript at this point, the more insulated you are from these risks. Whereas Node.js represents a pretty big footprint conceptually, using stripped-down, per-request, on-demand JavaScript solutions represents a much smaller footprint both technologically and conceptually. Companies are more easily able to integrate such things little-by-little, and also strip them out if problems arise. A re-architecture to Node.js and server-side JavaScript would both be more comprehensive and also more difficult to undo.</p>
<h4>Parting shots</h4>
<p><span class="me"><strong>Me:</strong> We&#8217;re almost out of time&#8230; do you have any final thoughts to share or clarify with the audience regarding Node.js and the middle-end?</span></p>
<p><strong>DA:</strong> I think your idea of <a href="http://blog.getify.com/2010/07/why-node-js-rocks-the-middle-end">using Node.js as a go-between &#8220;proxy&#8221; for middle-end tasks</a> is an interesting one. I think it represents probably the best possible scenario in which Node.js fits in with your &#8220;middle-end&#8221;.</p>
<p>But I&#8217;ll close by saying this: you must realize that Node.js may in fact be ushering in, at least for those (few) who are inclined and capable of taking up the banner, a new era of web applications. This era will be one defined by a blurring of the lines between front-end, middle-end, and back-end code. It will be a new class of web applications that is built end-to-end in JavaScript. In such a world, the middle-end tasks become the all-end tasks. So, more than anything, I think Node.js may mean there&#8217;s no need for a middle-end any more.</p>
<p>However, I think the reality is there will only ever be a select enlightened few who ever get to fully explore that new paradigm. For the overwhelming majority &#8220;rest of us&#8221;, the &#8220;middle-end&#8221; will still be a valid and important reality for our web applications, and as such, we should embrace this discussion.</p>
<p><span class="me"><strong>Me:</strong> Well said. I have nothing more to add, except a thank you to DA for joining us today. I know you&#8217;re a busy guy, so I&#8217;ll let you get on to other pressing debates.</span></p>
<style>.me { color:#663322; }</style>
]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/2010/07/node-js-the-end-of-the-middle/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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>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>JSON+Comments</title>
		<link>http://blog.getify.com/2010/06/json-comments/</link>
		<comments>http://blog.getify.com/2010/06/json-comments/#comments</comments>
		<pubDate>Wed, 23 Jun 2010 17:45:20 +0000</pubDate>
		<dc:creator>getify</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[crockford]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[json-p]]></category>

		<guid isPermaLink="false">http://blog.getify.com/?p=390</guid>
		<description><![CDATA[/* UPDATE: */
Found this old (from late 2005) post from Douglas Crockford himself on comments in JSON which I think validates the thinking I have presented here in this blog post. He says:

A JSON encoder MUST NOT output comments. A JSON decoder MAY accept and ignore comments.

This is exactly what I am advocating with this [...]]]></description>
			<content:encoded><![CDATA[<h4>/* UPDATE: */</h4>
<p><em>Found this old (from late 2005) <a href="http://tech.groups.yahoo.com/group/json/message/152">post from Douglas Crockford himself on comments in JSON</a> which I think validates the thinking I have presented here in this blog post. He says:</em></p>
<blockquote><p>
A JSON encoder MUST NOT output comments. <strong>A JSON decoder MAY accept and ignore comments.</strong>
</p></blockquote>
<p><em>This is exactly what I am advocating with this post. And JSON.minify() is simply one decent way to allow the JavaScript implementation of JSON.parse() to do the &#8220;MAY accept and ignore comments&#8221; thing.</em></p>
<h3>{</h3>
<p>Yesterday, I posted <a href="http://github.com/getify/JSON.minify">JSON.minify()</a> as a little mini open-source code snippet. The idea behind JSON.minify() is to be able to take a <em>JSON-like document</em> (that is, strict JSON + some other &#8220;stuff&#8221; which I&#8217;ll explain in a moment) and strip out/minify the document into something that is strictly valid, parseable JSON. This may seem like a crazy or mis-directed idea on the surface, but I have my reasons, which I&#8217;ll also explain in a moment.</p>
<p>Anyway, I started a fire-storm on twitter when I posted it. What ensued was a day-long barrage of tweets back and forth with many different people, most of whom seem to vehemently oppose the idea of there being any benefit to what I was trying to do. The mix seemed to be about 10% in favor, 90% opposed. Although, as the day and the tweet fest wore on, a few of the original &#8220;haters&#8221; did come to see <em>some</em> reasoning to my madness.</p>
<p>I&#8217;ve said many times before that it&#8217;s kind of flattering if someone &#8220;out there&#8221; cares enough about what you say to take the time to vocally disagree with you. Days like yesterday however make me re-think that position a little bit. In retrospect, I think the <em>problem</em> with this assertion in the age of twitter is that the barrier, the amount of energy it takes, to responding with &#8220;You&#8217;re wrong&#8221; is far less than it used to be even a couple of years ago. </p>
<p>Even blog commenting usually involves entering in your name, email, and website URL, or logging in, so it takes a slight amount more effort to do so than it does to click the reply icon and fire away.</p>
<h3>What &#8220;stuff&#8221;?</h3>
<p>To boil it all down, JSON.minify() is designed to strip out comments (single line // and multi-line /* &#8230; */) from a <em>JSON-like</em> document. Oh, and it also takes out any unnecessary white-space, if any exists. The white-space is not all that important to me, nor does it matter to the official JSON.parse() parser. But the comments&#8230; those are a different story.</p>
<p>You may wonder to yourself, &#8220;why would I want comments in my JSON? that only makes the JSON more bloated when it gets transferred.&#8221; Hold onto that question, because I&#8217;ll get to it in a moment. But for now, lemme say: <strong>I completely agree, retaining comments in <em>TRANSMITTED</em> JSON messages is a ridiculous idea.</strong> As a performance optimization nerd, it shouldn&#8217;t come as any surprise that I would feel that way. But strangely, many people <em>who know that about me well</em> seemed to forget that I would have a performance-minded opinion on this topic.</p>
<h3>Crockford&#8217;s &#8220;comments&#8221;</h3>
<p>Somewhat late in the day, <a href="http://twitter.com/tobie">@tobie</a> (via <a href="http://twitter.com/kangax">@kangax</a>) pointed me at <a href="http://developer.yahoo.com/yui/theater/video.php?v=crockford-json">the JSON saga</a> talk by Mr. JSON himself, Douglas Crockford. I invite you to take a few minutes and read through the transcript (or the 47 minutes to watch to the video), there&#8217;s some interesting stuff there.</p>
<p>About 1/3 of the way through the transcript, you&#8217;ll see Doug explain several reasons for why comments originally were allowed in JSON but were later removed. He says, in short, &#8220;people were using comments wrongly, so I removed them. Also, handling comments made the parser harder to implement, so I removed them. Also, comments didn&#8217;t exist in YAML and I wanted JSON to look like YAML, so I removed them.&#8221; If you go to the VERY end of the transcript, and read the last couple of sentences, you&#8217;ll see him boil it all down: </p>
<blockquote><p>
The main reason I took comments out was that I saw people who were trying to control what the parser would do based on what was in the comments, and that totally broke interoperability. There&#8217;s no way I could control the way they were using comments, so the most effective fix was to take the comments out.
</p></blockquote>
<p>I&#8217;ll just be honest with you. Those seem like crap reasons to me. Why do I say that? Him saying that he couldn&#8217;t control what people did with the parser is a spurious argument because he was in fact in control of the JSON &#8220;standard&#8221; and if it was ever going to take off it was going to be the way <em>he</em> wanted it to be. Somehow he magically got people not to implement JSON.parse() with extensions to the standard, so I&#8217;m not sure at all why he couldn&#8217;t keep them (by way of stern scolding, of course!) from using comments inappropriately. He had enough influence to keep JSON parsers to <em>his</em> standard, all he would have had to do was add &#8220;And comments shall only be ignored and not parsed.&#8221; to <em>his</em> standard and that would have been that.</p>
<p>I know that&#8217;s <em>easy</em> to say as &#8220;Friday-morning Quarterback&#8221; (like a decade later!) and I&#8217;m sure it was valid and made sense to him (and maybe others) at the time. But in my opinion, it was a wrong decision. Particularly frustrating is that Doug asserts in this talk: JSON is <em>never</em> going to change again because he intentionally didn&#8217;t version the format. So when <em>he</em> decided it was finished, he declared it sealed, and that&#8217;s just how it is. Imagine if WebKit got to decide &#8220;ok, &lt;canvas> is now final, no more changes!&#8221;</p>
<p>So, if we ever wanted to <em>add</em> to JSON, like putting comments back in, we can&#8217;t. He in fact says specifically, someday JSON will be replaced by something else <em>better</em>, but JSON will always remain as it is now. That&#8217;s a bold and unwavering statement&#8230; but knowing the personality of Crockford (who also by the way claims that HTML5 is crap and should be scrapped), I am inclined to believe that he&#8217;ll go to his death bed someday defending the rigidness of JSON never changing. But I do hope the eventual outcome of my ramblings is not to suggest that we need JSON+ or JSONX to succeed Crockford&#8217;s JSON.</p>
<p>It&#8217;s true that the JSON standard itself has been quite stable for a long time. But it&#8217;s also interesting to note from the transcript that he admits that the parser &#8220;technology&#8221; has evolved on several occasions. Namely, he progressively discovered various different &#8220;security holes&#8221; in what the parser would allow through, and so he added different regular expressions as filters in JSON.parse() to make the parsing safer.</p>
<h3>Comments don&#8217;t need to be part of the spec</h3>
<p>Now&#8217;s a good time for me to make my first assertion. Adding a simple set of regular-expression and state machine logic to strip out comments would not necessarily change the JSON spec. Granted, this proposal is not strictly the same as the regular expression filters that Doug put in for security holes, but it&#8217;s in a similar vein. It&#8217;s also quite like the parts of the parsing which ignore whitespace.</p>
<p>I&#8217;m not suggesting there be anything added to the JSON spec in terms of what is functionally allowed to be declared, or how properties and values are interpreted syntactically. In fact, I&#8217;m saying the opposite&#8230; what is taken as strict JSON <em>should not change at all</em>. In the same way that the whitespace is ignored during parsing, I&#8217;m suggesting comments should be too.</p>
<p>Comments are, in my opinion, a special beast. They should not be considered to have the same weight at all as other parts of the grammar/syntax. Comments are almost universally ignored by compilers/interpreters. We all know the primary use of a comment is for developer-friendly maintenance. </p>
<p>Look through the whole spec for JSON on <a href="http://json.org">json.org</a> and you&#8217;ll only find one tiny little statement at the bottom about whitespace: &#8220;Whitespace can be inserted between any pair of tokens.&#8221; He goes into quite detail with 3 different types of specifications for each part of the grammar/syntax, a few pages worth of text and diagrams, and then has one little off-handed sentence about how whitespace is basically not an important part of the grammar and is thus ignored. </p>
<p>In fact, there&#8217;s <strong>nowhere</strong> in any of JSON that whitespace has <em>any meaning at all</em> (well, whitespace is preserved inside of string literals&#8230; but it still has no <em>meaning</em> to the language).</p>
<h3>Comments ~= Whitespace</h3>
<p>I&#8217;d argue the same is true in practicality, and could officially be true if Crockford were so inclined, of comments. In my mind a comment is no more important or affecting of the &#8220;language&#8221; than is whitespace. If we can be tolerant of, ignore, and/or remove whitespace from a JSON string before parsing, why can&#8217;t we do the same of comments? All Doug would have to say is, &#8220;parsers <em>should</em> ignore comments just like they ignore whitespace.&#8221; It&#8217;s no more complicated than that.</p>
<p><strong>In fact, most parsers/compilers have a pre-processing step where they go through a source document and remove all whitespace AND comments before they apply any syntactic meaning to the tokens found.</strong> That&#8217;s because in almost every other language on the planet, comments are found to be useful to developers but irrelevant to machines and thus can be safely ignored.</p>
<h4>Can you imagine if Crockford had declared: &#8220;whitespace isn&#8217;t necessary in JSON, so the <em>parser won&#8217;t handle/ignore them at all</em>&#8220;?</h4>
<p>Whitespace serves no purpose at all in JSON other than readability (if you hand-author your JSON documents&#8230; more on that in a little bit). The same is true of comments&#8230; <strong>they are for readability <em>only</em>.</strong> That is the heart of my argument.</p>
<p>So, all this is to say&#8230; I think JSON parsing could easily be extended to support stripping of comments without affecting in any way shape or form the spirit of the JSON spec. Would <em>implementations</em> have to change? Yes. But they had to change several times before when Crockford found security holes, so I don&#8217;t see this as much different.</p>
<p>I&#8217;ve also proven the logic to strip comments is pretty straightforward&#8230; it&#8217;s a few hundred bytes and is implementable in pretty much any language I can think of that I&#8217;m familiar with. Even Doug admits in that talk he was never quite sure <em>why</em> implementors had trouble dealing with comments. Hint: bad programmers.</p>
<h3>Still not convinced.</h3>
<p>It&#8217;s ok if you (and Crockford) still disagree with me that comments should be able to be ignored by JSON.parse(). That doesn&#8217;t hurt my feelings at all. I still think they should, but let&#8217;s just set that issue aside and agree to disagree.</p>
<p>That battle not-withstanding, in my opinion, comments in a <em>JSON-like</em> document still have some <em>value</em> in some cases.</p>
<h3>JSON: file, document, message, database, etc?</h3>
<p>Let&#8217;s take a step back and broaden our view of what JSON can really be used for. Clearly, it&#8217;s primarily used as interstitial <em>messages</em> &#8212; that is, short little bursts of data interchange between different entities (like a server and browser). In fact, it&#8217;d be rightly argued that this is BY FAR the overwhelming usage of JSON.</p>
<p>Just like with XML, which has similar (but even less) flexibility in usage, JSON can be used in other ways other than data &#8220;transmission&#8221; in the traditional sense. For instance, JSON can be used as a database, a persistence layer for real data. There&#8217;s a whole slew of &#8220;no-SQL&#8221; type key-value pair databases that&#8217;s cropped up recently to latch onto this usage of JSON. In this case, JSON is never really &#8220;transmitted&#8221; but rather just parsed/filtered/transformed as the data needs to be accessed or mutated.</p>
<p>Though these valid use cases <em>do</em> exist, it seems that most people who were outraged at my little JSON.minify() at the heart of things just don&#8217;t agree with using JSON in a document/file context. They believe JSON should only be used for message transmission, and in that particular use case, clearly comments have no place. It&#8217;s only if you broaden your viewpoint that you&#8217;ll see the other uses for JSON which I&#8217;m asserting can benefit from comments.</p>
<h3>JSON for &#8220;data&#8221;</h3>
<p>JSON is, according to Doug, <em>just</em> intended to be a clean way to express key-value pairs in a structured and useful way that is universal to every language. He continues to say that the <em>primary</em> (although I don&#8217;t think <em>even he</em> would assert <strong>only</strong>) use-case is for transmitting that data.</p>
<p>He goes to great lengths to stress that JSON was, by stroke of sheer genius or alignment of the stars, an outward expression of an almost &#8220;natural law&#8221; of the universe (ie, computing/information science). He asserts that independently and at the same time, 3 different languages (JavaScript, Python, and Newtonscript) all arrived at <em>exactly</em> the same syntax for expressing a nestable data structure made up of keys and values.</p>
<p>The interesting thing about &#8220;data&#8221; is that it can take different forms as its uses varies. For instance, pure data is usually stored in a pure &#8220;database&#8221;. But this other animal, &#8220;meta-data&#8221;, which is usually used by programs to affect <em>how</em> they behave&#8230; it&#8217;s not so clear-cut how that data gets stored. But when those meta-data stores end up in files, it starts to make the usage of them a little bit more akin to a &#8220;document&#8221; than just pure data store.</p>
<p>A perfectly valid and long-held usage for key-value pair setting is configuration files. Almost every major web application framework in existence today, and an enormous amount of the web-related software (web, DNS, etc) out there, have taken their cues from the earliest days of Unix/Linux and used simple key-value pair configuration files.</p>
<h3>Consider PHP.ini or Apache&#8217;s httpd.conf</h3>
<p>These files have been around forever, and have for the most part always been about exposing configuration variables and letting administrators tinker with their values. Of course, every different piece of software defines it&#8217;s key-value pair syntax slightly differently. Some use =, others use :, some use quotes, some don&#8217;t, etc.</p>
<p>But you know what the other almost universal characteristic of these file formats is, besides the key-value pair syntax? That&#8217;s right, you guessed it. <strong>Comments!</strong></p>
<p>Why on earth would we do such a silly thing as to put comments in our configuration files? I heard various arguments to this affect on twitter yesterday, amounting to &#8220;the variable name should be descriptive enough to explain it&#8217;s possible values&#8221; or &#8220;if documentation for variables/values is needed, it belongs in a separate <em>document</em> called a manual.&#8221;</p>
<p>Well, I can&#8217;t really explain <em>why</em> like 99% of all web software went with flat configuration files (with comments!), but they did. And I&#8217;ll tell you, as one who regularly maintains my own web servers and thus web server software, I definitely appreciate having comments in my configuration files. I can&#8217;t imagine how painful editing PHP.ini or httpd.conf would be if I didn&#8217;t have comments right there inline explaining the various valid values and the implications of each.</p>
<h3>Configuration files and JavaScript</h3>
<p>If we now step back and look at the world of server-side JavaScript, we&#8217;ll see the revolution of JavaScript taking over in a lot of web software roles. But the fundamental paradigm of needing to configure this software still exists. We can configure it with command-line arguments when we start up the software, but most people who manage web software prefer to store commonly used configuration parameters in, gasp, a configuration file.</p>
<p>Does it make sense for the server-side JavaScript world to go out and define an entirely new and proprietary <em>format</em> for such flat, key-value pair configuration files? Umm, plainly, no. We should use JSON, right? That just makes sense to me! I figured it would to others too, but apparently I was wrong.</p>
<p>I had many people point me to examples of SSJS configuration files which were .js files. The curious thing to me when I looked at those .js files was that they almost all had a very interesting characteristic. They looked exactly like a JSON document, except for a little bit of extra &#8220;stuff&#8221;. Was that &#8220;stuff&#8221; complex JavaScript looping or operators? Nope. Was that &#8220;stuff&#8221; if-statements with conditional logic? Nope.</p>
<p>That &#8220;stuff&#8221; was comments. Huzzah! Oh, and yeah, that &#8220;stuff&#8221; was also something like an assignment of the JSON literal to a global JavaScript variable, or in some cases passing the JSON literal to a global function JSON-P style.</p>
<h4>But in spirit, this was a JSON document.</h4>
<p>It was designed to store meta-data, like configuration variables, in a structured key-value pair way. It had comments to help the developer understand/remember/maintain the document when necessary. The variable assignment (or function call parameter passing) really had almost nothing to do with the spirit of this document. It was more like a concession made to satisfy a pragmatic concern: If I parse a .js file as JavaScript, and all that file has in it is a JSON literal, the .js file will parse and &#8220;execute&#8221; validly, but that JSON object in it won&#8217;t be referenced anywhere in memory that I can <em>use</em>.</p>
<p>You see, the paradigm of needing to put the JSON into some variable or function parameter is the only <em>real</em> reason this file is a .js file and not a .json file. They could just as easily, and I would argue more cleanly, put <em>just</em> the JSON into the file, with no variable assignments or parameter/function calling, and then opened that file directly and read the contents into a string. At this point, with the JSON data in a string variable ready to be parsed, it&#8217;s no different than if we&#8217;d done an XHR call to grab that JSON into a string from the response text.</p>
<p>Regardless how it gets into the string, then they could pass that string to JSON.parse(), which is built into pretty much all server-side JS environments/engines, and the return value would be their created JSON object that they could assign to any appropriate local variable or pass to any other function.</p>
<h4>This would be cleaner, in my opinion, because it would not require any global variables or functions to make it work.</h4>
<p>Oh yeah, it was also <em>nice</em> that the JavaScript file parsing on their configuration files allowed for the files to have comments.</p>
<h3>Sounds familiar</h3>
<p>This is <em>exactly</em> the scenario that I found myself in with some recent server-side JavaScript. Could I have chosen to configure my SSJS application with .js files? Sure. Could I have chosen to pull the configuration from a database/datastore instead? Sure. Could I have chosen to just inline my configuration right into the code? Sure.</p>
<p>But all of these seemed like less than ideal to me. It seems so much cleaner to just have a simple JSON configuration file with key-value pairs to control my application&#8217;s behavior. And I foresaw that as my application grew in complexity, and as the possible valid values for those configuration parameters grew, I&#8217;d want to be able to rely on some inline comments to help keep the file more maintainable.</p>
<p>Not only that, but if someone else took and used my application some day, I&#8217;d want them to be able to configure it with relative ease. I certainly wouldn&#8217;t want them to have to be editing what looked like a code file (unless they too were a developer).</p>
<p>So, &#8220;config.json&#8221; file it was! Problem. If I put comments in, now I can&#8217;t parse the file. What do I do? Make a huge concession in the proper and clean design of my system and change to some other method of storing my configuration? Or do I take the lessened usability of my application and say that all &#8220;documentation&#8221; will just have to reside elsewhere, far away from the file it applies to?</p>
<h4>No, I decided, very simply, that adding comments to what was otherwise in every way imaginable a JSON document was the right approach.</h4>
<p>Call me crazy. String me up and lynch me. Let&#8217;s have a Salem witch trial. Let&#8217;s brand me for heresy.</p>
<p>And the simplest solution to my problem of comments being &#8220;invalid&#8221; in JSON was to create a simple filter, a &#8220;minifier&#8221; if you will, that could take otherwise valid <em>JSON-like</em> content, and strip it of comments so it was in fact valid pure JSON. This seemed like a decent and fairly graceful approach to my problem.</p>
<p>What followed on, and was the main point of the first half of this post, is that I truly believe that comments <em>should be allowed in pure JSON documents</em>. But since I&#8217;ll probably never win that argument with Crockford (or anyone else), the next best thing was that I defined this other thing which is <strong>INCREDIBLY SIMILAR TO JSON</strong>&#8230; namely JSON+Comments. I&#8217;m not much for silly overused acronyms, so I won&#8217;t go so far as to call it JSON+C. But you get the idea.</p>
<p>And here&#8217;s my very strict, and easy to enforce as a standard, definition:</p>
<pre style="background-color:#ddd;">
JSON+Comments: valid JSON + valid JS comments.
</pre>
<p>That&#8217;s it. Nothing more. Go smoke on that pipe for awhile.</p>
<p>I&#8217;m not trying to turn JavaScript into JSON. I&#8217;m trying to enhance JSON ever so slightly with comments. Oh, and I&#8217;m claiming that it&#8217;s so close to <em>real</em> JSON that this is a silly distinction/argument to make. But nonetheless, there you have it: JSON+Comments. And JSON.minify() is a handy tool to help &#8220;convert&#8221; your bastardized &#8220;JSON+C&#8221; into <em>real</em> JSON. Yay.</p>
<h3>JSON-P</h3>
<p>Let&#8217;s go back to JSON <em>messages</em> for just a moment. There&#8217;s actually more than one kind of JSON message. There&#8217;s strict JSON, which in practicality could only be transferred between server and browser through a direct Ajax call like with XMLHttpRequest().</p>
<p>But then there&#8217;s another emerged &#8220;standard&#8221; that we label JSON-P. JSON-P defines itself as JSON-with-padding. The &#8220;padding&#8221; is a little bit of a misnomer, in that it&#8217;s not &#8220;padding&#8221; (like, gasp, whitespace) but a function call that passes the JSON literal as a parameter. In fact, I&#8217;d argue it should have been JSON-W (JSON+wrapping) because the function call <em><strong>W</strong>raps</em> the JSON literal.</p>
<h4>JSON-P is <u>not</u> parseable by JSON.parse() or by any parser I know of except the JavaScript engine. And yet most of us definitely still relate it more to JSON than to JavaScript.</h4>
<p>When JSON-P came out, I&#8217;m sure some strict purists cringed and said (in a crotchety old voice) &#8220;That&#8217;s not JSON at all.. it&#8217;s just JavaScript&#8221;. And I guess there are those who still feel that way. But in all practicality, because of same-origin security issues primarily, JSON-P has actually emerged as a de-facto superset standard of JSON, but still a much restricted subset of true, full-blown JavaScript. It&#8217;s proven it&#8217;s usefulness beyond argument as a very valid and commonly used solution to cross-domain &#8220;Ajax&#8221;.</p>
<p><em>CAN</em> you do full JavaScript in a JSON-P message? Sure. But then that&#8217;s not really the intended spirit of JSON-P. Doing so would clearly put you in the realm of just plain ol&#8217; JavaScript. No, I&#8217;d argue there is a strictly definable JSON-P (though it has lacked a formal definition, just the de-facto patterns of use) which is this:</p>
<pre style="background-color:#ddd;">
JSON-P: valid JSON wrapped in a single function call.
</pre>
<p>There doesn&#8217;t have to be tolerance for JavaScript operations, boolean logic, try/catch&#8217;s, loops, or any of that other JavaScript goodness. JSON-P is a strict superset standard of JSON, and there&#8217;s no reason that it&#8217;s bad for doing so. It&#8217;s JSON + some other &#8220;stuff&#8221; that is helpful&#8230; in this case for bridging the cross-domain gap.</p>
<h4>Just because browsers (and parsers) don&#8217;t officially have, at this time, some actual JSON-P grammar/standard to apply to parsing JSON-P doesn&#8217;t mean it couldn&#8217;t be that way if we wanted to.</h4>
<p>For instance, we could quite easily <em>standardize</em> JSON-P like I&#8217;ve suggested, give it a website like &#8220;json-p.org&#8221; with fancy diagrams, and then take Doug&#8217;s JSON parser and add a few extra rules on top of it to allow for <em>only</em> the wrapping function call. The JSONP.parse() function could just check for the validity of the wrapping function call (&#8220;blah(&#8230;.);&#8221;) and then pass what&#8217;s in between the ( ) to the JSON.parse() function. We could even get some help from browser vendors to define a MIME/Type like &#8220;application/json-p&#8221;. </p>
<p>If a &lt;script> tag is found with that type, the contents (or the remote source file&#8217;s contents) could be checked against my simple JSON-P definition: look for a valid conforming function call, and take the parameter contents and validate it as <em>real</em> JSON.</p>
<h3>Wait a second</h3>
<p>That&#8217;s kind of crazy talk, huh? That actually makes JSON-P sound a lot like my outlandish JSON+Comments. It&#8217;s valid JSON, &#8220;decorated&#8221; by a very small amount of other &#8220;stuff&#8221; that&#8217;s there for simple but valid reasons. For JSON-P, the P is there for crossing the same-origin gap. For &#8220;JSON+C&#8221;, the comments are there for cases where commenting a file inline helps its readability/maintainability.</p>
<h3>}</h3>
<p>I&#8217;ve rambled on for quite a bit. Let me try to close this post down in a sensible way.</p>
<p>My idea to allow comments in what is otherwise a perfectly valid, parseable JSON <strong>file</strong> has <em>absolutely</em> no bearing on my feeling that such bloated JSON should <em>never</em> be transmitted. I&#8217;m not in any way suggesting that the JSON <em>messages</em> you send between systems should have comments in them.</p>
<p>I&#8217;m only saying that JSON files (like, configuration files) which reside in a file system and are generally and primarily only opened/read and nothing else, <em>can</em> benefit from having comments in them, just like almost all other configuration files do.</p>
<p>If for now (or even forever) the tradeoff is that this file must be slightly sanitized before being sent through Crockford.parse(), that&#8217;s something I&#8217;m willing to accept. I think the <em>slight</em> payoff, for my use case, is higher than the <em>slight</em> cost involved in the minification.</p>
<p>Also, this doesn&#8217;t preclude that JSON.minify() could be used in build processes to take developer-friendly &#8220;JSON+C&#8221; files and build them to <em>real</em> JSON files for use by the actual production system.</p>
<p>Lastly, I would say that JSON.minify() is good at removing whitespace from JSON &#8220;documents&#8221; too. For instance, if you have a templating system that builds up your JSON documents before they are sent out, that JSON document may end up with extra whitespace in it. Calling JSON.minify() on it before sending it over-the-wire is going to make the file smaller and transmit more efficiently. This is a good thing, right?</p>
<p><em>(yeah, I know, why would I build a JSON document from a text-based templating engine when I could have all my data in a data object variable and just call json_encode()&#8230;? You people just like to contradict everything. It&#8217;s possible even this crazy idea might have some merit, too, even if you wouldn&#8217;t dream of it.)</em></p>
<p>Now, I&#8217;m just wishing I&#8217;d called .minify() on this long post before publishing. Probably a lot of my &#8220;comments&#8221; here could/should have been stripped out. <img src='http://getiblog.2static.it/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h4>/* the end. duh. */</h4>
]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/2010/06/json-comments/feed/</wfw:commentRss>
		<slash:comments>8</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:10:30 -->