<?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>Blog &#124; Miller Medeiros</title>
	<atom:link href="http://blog.millermedeiros.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.millermedeiros.com</link>
	<description>A blog about design, code and some other stuff</description>
	<lastBuildDate>Thu, 16 May 2013 14:10:48 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Linked Lists for Dummies</title>
		<link>http://blog.millermedeiros.com/linked-lists/</link>
		<comments>http://blog.millermedeiros.com/linked-lists/#comments</comments>
		<pubDate>Wed, 15 May 2013 19:13:23 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[data structures]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1732</guid>
		<description><![CDATA[On high-level languages like JavaScript we usually don&#8217;t care about how the objects are stored in the memory, we let the VM handle it for us, and since the language contains Arrays most users never find a need for Linked Lists even tho it&#8217;s a very powerful and useful data structure. Like most front-end developers [...]]]></description>
				<content:encoded><![CDATA[<p>On high-level languages like JavaScript we usually don&#8217;t care about how the objects are stored in the memory, we let the <em>VM</em> handle it for us, and since the language contains Arrays most users never find a need for <a href="http://en.wikipedia.org/wiki/Linked_list">Linked Lists</a> even tho it&#8217;s a very powerful and useful data structure.</p>
<p>Like <em>most</em> front-end developers I don&#8217;t have a Computer Science degree and started to program using high level languages, it took me a while to stumble into Linked Lists, that&#8217;s why I&#8217;m going to explain the basic use cases, pros/cons of this simple data-structure and why it&#8217;s widely used. <small>- You probably used it before without knowing.</small></p>
<p>This post was motived by this tweet:</p>
<blockquote class="twitter-tweet"><p>Can anyone explain what a Linked List is and why I&#8217;d use one (if I even could in Ruby, PHP, JS). I&#8217;m not quite grokking their purpose?&mdash; integralist (@integralist) <a href="https://twitter.com/integralist/status/333517855909875712">May 12, 2013</a></p></blockquote>
<p><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script></p>
<p><span id="more-1732"></span></p>
<h3>Linked Lists are not <em>indexed</em></h3>
<p>The main difference from an Array is that Linked Lists are not indexed.</p>
<p>The Linked List doesn&#8217;t hold a reference to all the items that it <em>stores</em>, it usually only contain references to its <code>head</code> <small>(first element)</small> and/or <code>tail</code> <small>(last item).</small> Each item of the Linked List is responsible for storing a reference to the next and/or previous element of the list.</p>
<p>Not having indexes is the main advantage and drawback of Linked Lists.</p>
<h3>It doesn&#8217;t support arbitrary access</h3>
<p>The search and iteration over a linked list is <em>usually</em> sequential.</p>
<p>On an Array you can grab the 4th item by it&#8217;s index, like <code>myArray[3]</code>. Since the Linked Lists doesn&#8217;t contain indexes <small>(or references to all items)</small> you need to grab a reference to the <em>head</em> or <em>tail</em> of the list and iterate over the list items like <code>myLinkedList.head.next.next.next</code>.</p>
<p>As you can see, Linked Lists are not recommended when you need arbitrary access to the elements, in this case Arrays or Dictionaries/Hashes <small>(plain old JavaScript objects)</small> are better suited.</p>
<h3>Adding/removing items is usually <em>faster</em></h3>
<p>Adding and removing items from a non-indexed list is usually <em>faster</em> since it doesn&#8217;t need to <em>rebuild</em> the index every time the items change, it just needs to update the references to the <code>next</code> and/or <code>previous</code> element.</p>
<h3>Searching/iteration <strong>can</strong> be <em>slower/cubersome</em></h3>
<p>The lack of index and the simple structure can be a drawback, since you can&#8217;t skip to a certain <em>position</em> on the list some operations will require iterating over most nodes on the list or all of the list elements. <small>- There are always pros and cons.</small></p>
<p>Linked lists usually don&#8217;t contain helper methods like the ES5 Array methods <small>(map, reduce, some, forEach)</small> which can make things a little bit harder to manage <small>(you can implement it by yourself tho)</small>.</p>
<h3>Lower-Level languages</h3>
<p>Liked Lists are very common in lower level languages since you usually need to define how many bytes should be allocated for each object beforehand <small>(returning a pointer to that location in memory and making sure it doesn&#8217;t collide with other pointers).</small> Since linked lists doesn&#8217;t store a reference to all the items they can expand indefinitely without causing memory overlaps and items don&#8217;t need to be stored sequentially in memory or have the same size &#8211; it&#8217;s a very flexible data structure and very common because of that.</p>
<h3>Basic Implementation</h3>
<p>The very-minimal implementation of a linked list in JavaScript is:</p>
<pre class="brush:js">
// items of the list
var bird = {name:'Mockingbird'};
var cat = {name:'Keyboard'};
var dog = {name:'Fort'};
var duck = {name:'Scrooge'};

// the linked-list itself
var animals = {
    head : bird
};
// each item of the list stores reference to the next one
bird.next = cat;
cat.next = dog;
dog.next = duck;
</pre>
<p>To iterate over all items in the list you can simply do:</p>
<pre class="brush:js">
var animal = animals.head;
while (animal) {
    console.log(animal.name);
    animal = animal.next;
}
</pre>
<h3>The DOM is a Linked List</h3>
<p>The <a href="http://www.quirksmode.org/dom/w3c_core.html#domtree">DOM is a linked list</a>, you use <code>node.nextSibling</code>, <code>node.parentNode</code>, <code>node.firstChild</code>, etc to iterate over the elements. Linked Lists are very good for this use case since we add/remove items and rearrange the nodes many times during the application life cycle. It also simplifies the traversal a lot, navigating lists by index can be very cumbersome, <code>node.previousSibling</code> is way simpler than <code>nodesList[nodesList.indexOf(node) - 1]</code>.</p>
<h3>Doubly/Multiply/Circular Linked List</h3>
<p>Linked lists can have references to other elements besides the <code>next</code> element. It is specially useful when you need to iterate the list backwards or need to speed up some complex iteration/manipulation.</p>
<p>A Doubly Linked List is a list where the nodes also contains references to the previous elements.</p>
<pre class="brush:js">
// doubly-linked
cat.prev = bird;
dog.prev = cat;
// storing the tail (last item) is also useful in some cases
animals.tail = dog;
</pre>
<p>In a Multiply Linked List each node contains reference to 2 or more nodes. Circular lists have the <code>tail.next</code> point to the list <code>head</code> and are less common.</p>
<p>On <a href="https://github.com/millermedeiros/rocambole">rocambole</a> I use a doubly-linked list for the tokens <small>(<code>prev</code> and <code>next</code> references).</small> On the nodes I use a multiply linked list <small>(references to <code>parent</code>, <code>startToken</code>, <code>endToken</code>, <code>next</code> and <code>prev</code>)</small>, it simplifies the AST manipulation a lot and allows the creation of helper methods similar to jQuery very easily.</p>
<p>Cross references are extremely useful, don&#8217;t let the lack of index be a limitation, abuse it when needed.</p>
<h3>Removing/Adding Items</h3>
<p>Another big advantage of linked lists is that if you add/remove items during the iteration it usually doesn&#8217;t cause undesired side effects, imagine this scenario:</p>
<pre class="brush:js">
var animals = [bird, cat, dog, duck];
for(var i = 0, n = animals.length; i < n; i++) {
    // OOPS! TypeError!
    // length changed during iteration, animals[3] doesn't exist anymore.
    var animal = animals[i];
    console.log(animal.name);
    if (animal.name === 'Fort') {
        animals.splice(i, 1);
    }
}
</pre>
<p>If you used a Linked List (or didn't cached the <code>animals.length</code> value) this problem wouldn't exist, removing items from a linked list doesn't break the iteration:</p>
<pre class="brush:js">
var animal = animals.head;
while (animal) {
    console.log(animal.name);
    if (animal.name === 'Fort') {
        removeItem(animals, animal);
    }
    animal = animal.next;
}

// to remove an item we just need to remove all references to it
function removeItem(list, item){
    // assuming that list is doubly-linked
    if (list.head === item) list.head = item.next;
    if (list.tail === item) list.tail = item.prev;
    if (item.prev) item.prev.next = item.next;
    item.next = item.prev = null;
    // on a singly-linked list the process is more expensive since you need to
    // loop over the items to find out where to remove
}
</pre>
<h3>Sum Up</h3>
<p>I hope it was clear enough and that you find some good use for it. I find it really important to learn about data structures and other <em>computer sciency</em> subjects, you never know when this kind of knowledge can be useful and a lot of smart people already thought about these problems before, it's good to have options.</p>
<p>Wikipedia contains a <a href="http://en.wikipedia.org/wiki/Linked_list#Tradeoffs">detailed explanation of the pros/cons</a> in case you are interested in getting all the details. <small>(not for dummies tho)</small>.</p>
<p>You could also create a generic implementation that works for multiple cases but that is outside the scope of this article, I tried to keep it as simple as possible just to explain the concept and not a specific implementation <small>- a <a href="https://www.google.com/search?q=javascript+linked+list">quick Google search</a> returned many results.</small> I have an <a href="https://github.com/millermedeiros/MM_js_lib/blob/master/src/other/LinkedList.js">old implementation</a> on my personal files but to be honest I'm not using it on any projects and nowadays I would build it in a different way <small>- make it a doubly linked list, remove the iteration helpers and simplify the structure (there is no need for a wrapper object for each node, <code>prev</code> and <code>next</code> are very unlikely to cause name collisions). Maybe one day I update it and release as a separate project...</small></p>
<p>That's it!</p>
<p><ins datetime="2013-05-16T13:59:03+00:00"><strong>Edit 2013/05/16:</strong> Simplified <code>removeItem</code> implementation and moved it into it's own section.</ins></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/linked-lists/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Improving Vim auto complete for CSS class names</title>
		<link>http://blog.millermedeiros.com/vim-css-complete/</link>
		<comments>http://blog.millermedeiros.com/vim-css-complete/#comments</comments>
		<pubDate>Wed, 24 Apr 2013 22:23:48 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[protip]]></category>
		<category><![CDATA[vim]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1713</guid>
		<description><![CDATA[Just a quick tip about Vim autocompletion. I&#8217;ve been using the excellent SuperTab Vim Plugin for a couple years, it works reasonably well (autocompletes based on words from all buffers, file names, tags, context, etc&#8230;) but it doesn&#8217;t work really well for text that is split by dashes - CSS contains lots of these&#8230; - [...]]]></description>
				<content:encoded><![CDATA[<p>Just a quick tip about Vim autocompletion.</p>
<p>I&#8217;ve been using the excellent <a href="https://github.com/ervandew/supertab/">SuperTab Vim Plugin</a> for a couple years, it works reasonably well (autocompletes based on words from all buffers, file names, tags, context, etc&#8230;) but it doesn&#8217;t work really well for text that is split by dashes <small>- CSS contains lots of these&#8230; -</small> so I started to get frustrated with it.</p>
<p>You can change the auto complete behavior with <code>set iskeyword</code> which also changes the behavior of standard motion commands like <code>w</code>, <code>e</code>, <code>b</code> (it changes the word delimiters) &#8211; which a find a PITA since I got used to these motions. My quick and dirty solution to the problem was to keep <code>iskeyword</code> with the minimal value as possible and only change it during <code>InsertEnter</code>.  That way I can still use <code>cw</code>, <code>ve</code>, <code>db</code> to edit each <em>fragment</em>, autocomplete will work properly for words like <code>foo-bar__baz</code>, and you can still use <code>W</code>, <code>B</code> and <code>E</code> if you want to quickly jump around. For me that&#8217;s the best of both worlds!</p>
<p><span id="more-1713"></span></p>
<pre><code>
function! KeywordsAll()
    setl iskeyword=@,48-57,192-255,\@,\$,%,-,_
endfunc

function! KeywordsBasic()
    setl iskeyword=@,48-57,192-255
endfunc

" improve the 'search word under cursor' behavior
nnoremap * :silent call KeywordsAll()<CR> * :silent call KeywordsBasic()<CR>
nnoremap # :silent call KeywordsAll()<CR> # :silent call KeywordsBasic()<CR>

augroup is_keyword
  " clear commands before resetting
  autocmd!
  " make sure `complete` works as expected for CSS class names whithout
  " messing with motions (eg. '.foo-bar__baz') and we make sure all
  " delimiters (_,-,$,%,.) are treated as word separators outside insert mode
  autocmd InsertEnter,BufLeave * :call KeywordsAll()
  autocmd InsertLeave,BufEnter * :call KeywordsBasic()
  " yes, we need to duplicate it on VimEnter for some weird reason
  autocmd VimEnter * nnoremap * :silent call KeywordsAll()<CR> * :silent call KeywordsBasic()<CR>
  autocmd VimEnter * nnoremap # :silent call KeywordsAll()<CR> # :silent call KeywordsBasic()<CR>
augroup END
</code></pre>
<p>And here are my other autocomplete settings:</p>
<pre><code>
set infercase
set completeopt=longest,menuone
set omnifunc=syntaxcomplete#Complete
set completefunc=syntaxcomplete#Complete
set complete=.,w,b,u,U,t,i,d

augroup omni_complete
  " clear commands before resetting
  autocmd!
  " Enable omnicomplete for supported filetypes
  autocmd FileType css,scss setlocal omnifunc=csscomplete#CompleteCSS
  autocmd FileType html,markdown setlocal omnifunc=htmlcomplete#CompleteTags
  autocmd FileType javascript setlocal omnifunc=javascriptcomplete#CompleteJS
  autocmd FileType python setlocal omnifunc=pythoncomplete#Complete
  autocmd FileType xml setlocal omnifunc=xmlcomplete#CompleteTags
augroup END
</code></pre>
<p>I&#8217;m not using any plugin to generate JavaScript or CSS tags so my code completion is mostly based on all words contained on all the open buffers. Because of the way I structure my code nowadays, I hardly need more than that.</p>
<p>PS: I don&#8217;t recommend Vim to a new developer for the same reasons as <a href="http://delvarworld.github.io/blog/2013/03/16/just-use-sublime-text/">described in this post</a>, even tho I can&#8217;t see myself using another editor nowadays&#8230; &#8211; here is my <a href="https://gist.github.com/millermedeiros/1262085">complete .vimrc</a> + some links in case you are interested.</p>
<p><ins datetime="2013-04-25T15:30:07+00:00"><strong>Edit (2013/04/25):</strong> changed <code>autocmd</code> to be triggered on <code>BufEnter</code> and <code>BufLeave</code> to improve complete across all open buffers.</ins><br />
<ins datetime="2013-05-01T15:49:46+00:00"><strong>Edit (2013/05/01):</strong> improved <code>*</code> and <code>#</code> behavior.</ins></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/vim-css-complete/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mout &amp; Modularity</title>
		<link>http://blog.millermedeiros.com/mout-and-modularity/</link>
		<comments>http://blog.millermedeiros.com/mout-and-modularity/#comments</comments>
		<pubDate>Tue, 05 Mar 2013 07:08:35 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[amd]]></category>
		<category><![CDATA[best practices]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[opensource]]></category>
		<category><![CDATA[resources]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1663</guid>
		<description><![CDATA[Discussions about modularity are recurrent. Some people say that each function should be a separate module/file/package; others say that methods should be contained by a package and grouped by similarity/concerns; and there is still a 3rd group that thinks that a single namespace is the way to go. I will try to explain the design [...]]]></description>
				<content:encoded><![CDATA[<p><a href="http://moutjs.com"><img src="http://blog.millermedeiros.com/wp-content/uploads/2013/03/mout-logo.png" alt="" title="mout-logo" width="630" height="250" class="alignnone size-full wp-image-1679" /></a></p>
<p>Discussions about modularity are recurrent. Some people say that each function should be a separate module/file/package; others say that methods should be contained by a package and grouped by similarity/concerns; and there is still a 3rd group that thinks that a single namespace is the way to go. I will try to explain the design decisions that influenced the creation and current structure of <a href="http://moutjs.com">moutjs</a> and why single function packages are not always the <em>best</em> solution.</p>
<p><span id="more-1663"></span></p>
<h3>How it started</h3>
<p>It all started back in 2009, when I decided to extract and port some common methods that I used in different projects into reusable packages. I started by creating a <code>stringUtils</code> and <code>arrayUtils</code> namespaces and adding new methods as needed.  The helpers grew at each project and after a few months I had more than 20 functions inside the <code>stringUtils</code> namespace <small>(some of them pretty large since they handled HTML entities conversion)</small>, which means I had to load the 20+ functions even if I only needed a single method <small>- keep in mind that I do mostly front-end development and at the time I was coding mobile sites very often, file size was a big concern.</small></p>
<pre class="brush:js">
// used a long (global) namespace to avoid name collisions
// loaded all methods even if not used by the app
MM.arrayUtils.forEach(arr, doSomething);
var slug = MM.stringUtils.hyphenate(myStr);
</pre>
<h3>Going modular</h3>
<p>At the end of 2010 I was working on bigger JavaScript projects <small>(+10K LOC)</small> and started to use <a href="http://requirejs.org">RequireJS</a> to manage my dependencies, and by doing so I was motivated to split my code into smaller files, that way I could keep the code organized and load only what was actually being used by the app. That enhanced my JavaScript development experience a lot, I was able to write apps with more than 50K lines of code with ease, code reuse increased exponentially at each project, no more conflicts when working with other devs and specially no more reliance on globals <small>- I do a lot of projects that need to run inside bigger sites/apps, relying on globals is a path that usually leads to pain.</small></p>
<pre class="brush:js">
// require a single method (recommended)
var forEach = require('mout/array/forEach');
forEach(arr, doSomething);
// or the whole package if you want to (I rarely do this)
var stringUtils = require('mout/string');
var slug = stringUtils.hyphenate(myStr);
</pre>
<h3>Why a single package?</h3>
<h4>The state of front-end Package Managers</h4>
<p>One of the main reasons to keep mout as single package is that package management for the front-end is still in flux. Some people been using npm while others use bower/volo/jamjs, so it&#8217;s hard to get into a <em>common ground</em>. Adopting one package manager over another might cause some potential users to not use the lib, since that might not be their preferred approach or just not how they are handling dependencies. <small>- node.js people, mind yourself that not everyone is writing node.js apps, so npm and cjs modules are not the silver bullets that you guys like to pretend they are.</small></p>
<p>Distributing a single package is easier for consumption in the browser, since you can just download a zip/tarball into the right folder and call it a day. In fact I&#8217;ve been using some <a href="https://gist.github.com/millermedeiros/3859714">very basic shell scripts</a> to download/update my dependencies over the past couple years and it&#8217;s working pretty well for packages that have a shallow dependency tree.</p>
<h4>Git submodules are a pain to maintain</h4>
<p>The package manager isn&#8217;t the only reason, there is also the fact that maintaining multiple git repositories can be a huge PITA. <em>Everyone</em> knows that git submodules doesn&#8217;t work that well and there are some things that are just simpler when you deal with a single repository <small>(mout contains ~200 methods).</small> Things like scaffolding, automation and running tests is easier since you have less moving parts <small>- single build script, single test runner, single CI server, etc.</small></p>
<p>The <a href="https://github.com/mout/mout/blob/master/build.js">mout build script</a> is responsible for keeping all packages up-to-date before running the tests, if a module doesn&#8217;t contain tests it creates a failing spec automatically to warn you. It also contains some scaffolding commands to create new modules based on templates and a command to help deploy the project. That is the kind of automation that is easier to implement if the project follows a <em>sane</em> structure.</p>
<p>PS: I know npm doesn&#8217;t require all packages to be separate git repositories <small>(you don&#8217;t even need a public repository),</small> but if they aren&#8217;t separate repositories then it probably shouldn&#8217;t be a separate package as well.</p>
<h4>Consistency</h4>
<p>The main reason why code reuse is such a hard thing to achieve is because most libraries/frameworks aren&#8217;t designed to work together and makes a lot of assumptions on how they will/should be used. Since everything is coded together there is a reduced chance of naming conflicts and you also increase the consistency/cohesion between all functions (including naming conventions). It motivates code reuse between internal modules as well.</p>
<p>Some bugs and enhancements affects multiple modules at once, having a decentralized issue tracker can lead to many duplicates and also makes it harder for users/maintainers to follow the progress. As an example we decided to <em>borrow</em> a feature from Lo-Dash on mout v0.4, the ability to use a shorthand notation on most array/object/collection methods, so you can do <code>find(users, {name:'john'})</code> instead of <code>find(users, function(u){return u.name === 'john'})</code>. This change affected 18 modules and required 2 new methods (1 private). This is the kind of change that should be done <em>across the board</em>, all at once. Releasing 20 packages !== fun. If each package was maintained by different users it would surely not work since we could never get into an agreement if this feature should really be implemented or even coordinate a release date&#8230;</p>
<p>If each method accepts a different set of arguments <small>(or different order)</small> and/or are named following different conventions you will probably make more mistakes. Common conventions means less time spent reading the docs or fixing silly bugs.</p>
<h4>Less bureaucracy</h4>
<p>Since everything is part of the same package, it&#8217;s easier to handle the dependency on the &#8220;project context&#8221; and still require individual methods as needed. If every single function was a separate package you would need to list it twice, once on the <code>package.json</code> and another every time you <code>require</code> the module.</p>
<h4>&#8220;Discoverability&#8221;</h4>
<p>Since everything is part of the same package you increase the chance of the user to discover that feature. There are many functions that aren&#8217;t popular and the user would never find out they existed, or how useful they are. Sometimes you don&#8217;t know you <em>need it</em> until you <em>see it</em>. How can you find something if you don&#8217;t even know what you are looking for?</p>
<p>It means less time spent <em>hunting</em> for packages. You can trust that all functions have somewhat the same quality level and are meant to work together.</p>
<p><img src="http://blog.millermedeiros.com/wp-content/uploads/2013/03/pkg-damn_high.jpg" alt="" title="the amount of packages is too damn high!" width="630" height="610" class="alignnone size-full wp-image-1693" /></p>
<h4>Project goals</h4>
<p>I created mout with the intention of using it as a <em>replacement</em> to the JavaScript Standard Library, where you don&#8217;t need to worry about browser quirks and can use all methods in all environments <small>(IE 7+)</small> with a good amount of confidence.</p>
<p>Since it&#8217;s meant to be a &#8220;standard lib&#8221; you wouldn&#8217;t expect it to be scattered across multiple places.</p>
<h4>Cross dependencies</h4>
<p>There are a lot of cross dependencies between modules. Handling it between multiple separate projects would be a tricky thing, specially for browsers.</p>
<p><a href="http://blog.millermedeiros.com/wp-content/uploads/2013/03/mout-graph.png"><img src="http://blog.millermedeiros.com/wp-content/uploads/2013/03/mout-graph_s.png" alt="" title="mout dependency graph" width="630" height="538" class="aligncenter size-full wp-image-1676" /></a><br />
<small>Dependency graph generated with <a href="https://github.com/pahen/node-madge/">node-madge</a> (excluded packages to make it easier to identify real dependencies).</small></p>
<h4>&#8220;Identity&#8221;</h4>
<p>Multiple packages doesn&#8217;t hold any &#8220;identity&#8221; and probably won&#8217;t create a strong sense of &#8220;community&#8221;.</p>
<h3>Why AMD as the authoring format?</h3>
<p>The authoring module format is just a detail. It can be easily translated into any other module format if needed.</p>
<p>Since I do mostly front-end development it makes more sense to write the modules in a format that works in the browser without needing a build. It also makes the whole deployment process easier. Since most node.js modules are installed through npm, we can <a href="https://github.com/millermedeiros/nodefy">convert it into a node.js compatible format</a> during <code>npm publish</code> and make sure that the users will get the files they need without any extra overhead <small>(no performance or readability drawbacks).</small> Since the browser package managers usually use the git repository as the source <small>(don&#8217;t have something similar to <code>npm publish</code>)</small> it&#8217;s better to leave the files on github always ready for browser consumption.</p>
<h3>There are no silver bullets</h3>
<p><strong>mout</strong> have very specific goals and needs, that&#8217;s why it&#8217;s coded in this specific way. The reasoning described above surely doesn&#8217;t apply to all projects, in fact I believe it applies to the minority.</p>
<p>I truly believe that single function modules will become more popular in the following years, but it surely isn&#8217;t how I write most of my application code. Not all code need to be reused in different contexts, and modularity is not always an advantage <small>(sometimes it can be an extra layer of bureaucracy).</small> Consider the options and pick the one that fits better your needs.</p>
<p>My rule of thumb nowadays is that if something doesn&#8217;t help me it will probably slow me down. I won&#8217;t follow some specific convention/pattern/dogma just because other people say <em>it&#8217;s the right thing</em> unless I think it does apply to my own scenario. Working on a <em>fast paced environment</em> with many changes during the development process made me become more pragmatic about how I approach problems, same rule might not apply to yourself.</p>
<blockquote><p>
  &#8220;It just works&#8221; is fantastic, when it really does just work. But it&#8217;s brutal when it doesn&#8217;t actually work. Then I prefer transparency. &#8211; @JohnDCook
</p></blockquote>
<h3>Give it a try</h3>
<p>mout contains many useful features, consistent API, good documentation and is being actively maintained. We also have an extensive set of unit tests to ensure correctness. Expect even more features in the coming months and a fast release cycle. We&#8217;ve been working hard to make it as awesome/reliable as possible. Check it out at <a href='http://moutjs.com'>http://moutjs.com</a> and <a href="http://github.com/mout/mout">star/fork the project on github</a>. We are also on the <strong>#moutjs</strong> channel on <a href="http://webchat.freenode.net/?channels=moutjs">irc.freenode.net</a>.</p>
<h3>Further reading</h3>
<ul>
<li><a href="http://blog.millermedeiros.com/keep-your-modules-and-functions-small/">Keep your modules and functions small</a></li>
<li><a href="https://gist.github.com/substack/5075355">substack opinion about single function packages</a> <small>(external)</small></li>
<li><a href="http://www.position-absolute.com/articles/death-to-monolithic-libraries/">Death to monolithic libraries</a> <small>(external)</small></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/mout-and-modularity/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>My jQuery Wish List</title>
		<link>http://blog.millermedeiros.com/jquery-wish-list/</link>
		<comments>http://blog.millermedeiros.com/jquery-wish-list/#comments</comments>
		<pubDate>Thu, 20 Dec 2012 16:08:44 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[rant]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1640</guid>
		<description><![CDATA[Haters gonna hate but I&#8217;ve been delaying for too long to write this one. Since the jQuery team is working to get the version 2.0 out of the door and Christmas is coming it might be a good time to talk about it. Please don&#8217;t add comments like &#8220;use framework/library X instead!&#8221;, the question here [...]]]></description>
				<content:encoded><![CDATA[<p><em>Haters gonna hate</em> but I&#8217;ve been delaying for too long to write this one. Since the jQuery team is working to get the version 2.0 out of the door and Christmas is coming it might be a good time to talk about it. Please don&#8217;t add comments like &#8220;use framework/library X instead!&#8221;, the question here is not about which framework/library is better but about things that <em>I think</em> could be improved.</p>
<p>I know that jQuery 2.0 will have the same API as 1.9, this wishlist would be for a future version of jQuery that doesn&#8217;t need to be backwards compatible <small>(call it jQuery <em>Harmony</em> or jQuery 3.0 if you will).</small></p>
<p><span id="more-1640"></span></p>
<h3>Consistency</h3>
<p>I used jQuery on most projects for the past 5 years and I still get confused with some methods. I think that a good part of it is because some methods/options are poorly named and also because most functions have a LOT of faux-overloads. The fact that every single method is in the same <em>namespace</em> and that everyone thinks that everything should be a plugin, amplifies this problem as well.</p>
<h4>add()</h4>
<p>What would you expect when you call a method <code>add()</code> on a collection? My initial thought would be that it append the new elements to the end of the collection, just like <code>Array#push</code> does. Of course if the collection is a <em>jQuery collection</em> I would be wrong.</p>
<pre class="brush:js">

var lists = $('ul');
var allLists = lists.add('ol');
console.assert( lists === allLists ); // false, it returns a new collection!
</pre>
<p>Since it returns a new collection <code>concat</code> or <code>join</code> would be better names.</p>
<h4>map() / each() / filter()</h4>
<p>Arguments order is reverse than what I would expect, there are native Array methods with similar names and different behavior.</p>
<pre class="brush:js">

// how it is
$('.foo').each(function(index, element){
    ...
});
// how I expect it to be
$('.bar').each(function(element, index){
    ...
});
</pre>
<p>I rarely need the index but I need a reference to the element 99% of the times. And no, don&#8217;t tell me to use <code>this</code> to reference the element (<a href="http://blog.millermedeiros.com/avoiding-the-this-keyword-on-jquery/">I avoid it</a>).</p>
<p>It should also accept a 2nd argument to set the context (<code>this</code> keyword) value, just like the ES5 Array methods.</p>
<h4>is() / not() / has()</h4>
<p>Ok, this one used to get me all the time. Almost all methods inside the <a href="http://api.jquery.com/category/traversing/">traversing category</a> on the documentation returns new collections, they are basically ways to filter the matched elements, grab siblings/parent elements, add new elements to the collection &#8211; basically anything that changes the matched elements &#8211; but of course there are exceptions to the rule.</p>
<p>By looking at the names <code>is</code>, <code>not</code> and <code>has</code> you would expect the return value from the 3 methods to be similar, guess what? they aren&#8217;t. <code>is()</code> returns a boolean, <code>not()</code> and <code>has()</code> filters the collection. Very counter intuitive.</p>
<p><code>not()</code> is the opposite of <code>filter()</code>, by looking at the name I would expect it to be the opposite of <code>is()</code>. Better name for <code>not()</code> would be <code>reject()</code>, <code>exclude()</code>, <code>discard()</code>, etc&#8230;</p>
<p>I also think that <code>has()</code> gives an idea that the return value will be a boolean: &#8220;does X has Y?&#8221;. This one might need a two word name to be descriptive, even a bad name like <code>ifHas()</code> would solve the return ambiguity. The method <code>has()</code> should be similar to <code>is()</code>, it should return <code>true</code> if any of the matched elements have a descendant that matches the selector or maybe even better, should be called <code>hasDescendant()</code>.</p>
<h4>contents() / children()</h4>
<p>I&#8217;m not a big fan of method overload and I also don&#8217;t like booleans as arguments (boolean trap) but this is the case where I think a boolean on <code>children()</code> would be better than a new method named <code>contents()</code>. I have no idea what <code>contents</code> returns, is it a string? does it require any arguments? is it a setter or getter or both? Name it <code>getChildren()</code> and <code>getAllChildren()</code>, problem solved.</p>
<h3>Better names</h3>
<p>Descriptive names can reduce the need of a documentation, it also makes the API discovery process way easier, you can guess what the method does just by looking at the name. Besides the lack of consistency on the previous examples jQuery also contains many methods that are poorly named. Just to cite a few:</p>
<h4>jQuery.inArray()</h4>
<p>Why? I don&#8217;t even&#8230; A method called <code>inArray</code> returns an integer (<code>-1</code> if not found), this should be called <code>indexOf</code> or return a proper boolean value, no excuses for it.</p>
<h4>jQuery.proxy()</h4>
<p>This method should be called <code>bind</code> since it is similar to the ES5 <code>Function#bind</code>, proxy is an overloaded term in programming (design pattern, proxy server, &#8230;) and should not be used to describe something that have a popular/alternative name.</p>
<h4>jQuery.extend()</h4>
<p>You are not extending an object, you are augmenting it with properties from another one. This is a helper for mixIns. <code>mixIn</code> or <code>merge</code> would be better.</p>
<h4>toggle()</h4>
<p>Toggle what? class name? display? visibility? state? Is this method really needed?</p>
<h4>jQuery.param()</h4>
<p>This name isn&#8217;t really descriptive; <code>query</code>, <code>objectToQuery</code>, <code>serialize</code> would be better. Note that <code>serialize</code> would conflict with a existing method but that method should also have a better name (<code>serializeForm</code>, <code>serializeFormAsArray</code>, <code>formToQuery</code>).</p>
<h3>$.Callbacks</h3>
<p>Callbacks are a dumbed down version of a Signal with a few <em>mistakes</em>.</p>
<p>Flags being a string is error prone and awkward.</p>
<pre class="brush:js">

// ops, typo and multiple spaces. silent failure.
var cb = $.Callbacks('once  memoy');
</pre>
<p><code>fireWith()</code> is <em>weird</em> since all the callbacks will be called on the same context and it can cause conflicts, you need to know the structure of all the callbacks beforehand and it deceives the decoupling logic, the event dispatcher shouldn&#8217;t know about the handlers implementation&#8230; Setting context during <code>add()</code> would be better.</p>
<p><code>disable()</code> and <code>lock()</code> seems redundant and doesn&#8217;t have options to re-enable/unlock.</p>
<p>Callbacks should be replaced by <a href="http://millermedeiros.github.com/js-signals/">js-signals</a>, better API, better implementation, more flexible and less error prone.</p>
<h3>$.Deferred</h3>
<p>Follow the <a href="https://github.com/promises-aplus/promises-spec">Promises/A+ spec</a>. kthx, bye.</p>
<h3>Animation</h3>
<p>Make it better, faster, stronger. The queue system is nice in some cases but most of the times it is a huge PITA. Multiple consecutive calls trigger multiple animations, I don&#8217;t think we should need to call <code>stop(true)</code> every time we want to toggle the animation. If you don&#8217;t know what I mean just <a href="http://jsbin.com/uyudoy/1/edit">check this jsbin</a>.</p>
<p>I also think it should provide an easy way to reuse the methods without triggering all the hooks so I could tween any numeric values without overhead. There is no reason why the animation module should be tight coupled with the DOM.</p>
<p>This is a part of jQuery that I would probably throw away and start from scratch.</p>
<h3>Ajax</h3>
<p>Please fix this. Too many options and some really bad names, I always need to check the documentation to use it and I always commit mistakes that are hard to track, mostly due to misspelled/invalid options.</p>
<p>Just look at the <a href="http://api.jquery.com/jQuery.ajax/">documentation</a>, 33 options! Nobody will ever remember all of them, that is fine, as long as the frequently used ones are easy to guess and if I pass an invalid option it tells me that I&#8217;m wrong, unfortunately that is not the case.</p>
<p><code>data</code> sets which arguments should be sent together with the request (query string or POST body), so why <code>dataType</code> and <code>dataFilter</code> are related to the response? <code>contentType</code> is used to set the request content type. <code>contents</code> is used to parse the response&#8230; Please keep names consistent, if you use a prefix/word for the request don&#8217;t use it as well for the response.</p>
<p>If I had a penny for each time I try to use <code>method: "POST"</code> instead of <code>type: "POST"</code> I would have almost $1. In my head GET, POST, PUT, DELETE are <a href="http://en.wikipedia.org/wiki/HTTP#Request_methods">request methods</a>, not types.</p>
<h4>ajaxError / ajaxSend / ajaxStop / ajaxError</h4>
<p>These should be signals/$.Callback so you could add/remove listeners, set priority, etc:</p>
<pre class="brush:js">

jQuery.on.ajaxError.add(logAjaxError);
// later in the code we can remove listener
jQuery.on.ajaxError.remove(logAjaxError);
</pre>
<p>I rarely use this, but sometimes it can be useful for logging and/or for generic error handling. For debugging <a href="http://www.charlesproxy.com/">Charles Proxy</a> and <a href="https://developers.google.com/chrome-developer-tools/docs/network">Dev Tools Network Panel</a> are way more useful.</p>
<h3>Less method overloads</h3>
<p>Some jQuery methods have more than 5 <em>overloads</em> based on the arguments that are passed. Having optional parameters and accepting a couple different arguments types can make things simpler but it surely shouldn&#8217;t be abused. The <code>jQuery()</code> method is the biggest offender, you can pass selectors, elements, object, jQuery instance, function, HTML string&#8230; &#8211; This should be split into at least 3 distinct methods, being brief is not always a good thing.</p>
<p>My point is that it is harder to read the code afterwards if you aren&#8217;t familiar with the different signatures of the method. Discovering the API is also harder and requires constant checks on the documentation.</p>
<h3>Modularity</h3>
<p>The <a href="https://github.com/jquery/jquery#how-to-build-your-own-jquery">custom build</a> (added on v1.8) was a good step forward but still not good enough. I don&#8217;t want to load the whole library just to use a few methods, I also don&#8217;t want to manually check what is being used and sometimes we only use a small subset of a &#8220;module&#8221;.</p>
<p>I know it is hard to split everything and that there are a lot of cross-dependencies on the internal code, but it just doesn&#8217;t feel right. On most projects I probably use less than 20 methods &#8211; <code>filter</code>, <code>closest</code>, <code>toggleClass</code>, <code>remove</code> and <code>$</code> gets 70% of the job done.</p>
<p>I know I could use Google Closure Compiler Advanced Mode to remove the unused code branches but in some cases that isn&#8217;t possible. In the past couple years I worked on projects that required a substantial amount of JavaScript (20-50K LOC) and lazy loading some parts of the app was essential for the performance, creating an <em>externs</em> file can be tricky and not really easy to maintain in the long run, besides the fact that I use AMD modules on almost all projects which makes it even harder.</p>
<p>I would like to see complete modularity, being able to require a single method and use it as a standalone function:</p>
<pre class="brush:js">
var $ = require('jquery/$');
var foo = $('.foo');
// loading a new method would augment the `jQuery.prototype`
var find = require('jquery/dom/find');
foo.find('.bar');
// but also work as a standalone function
find(foo, '.bar');
</pre>
<p>That way it is clear that my module depends on methods XYZ and my build will take care of bundling only what is being used. You can also use a tool like <a href="https://github.com/pahen/node-madge/">node-madge</a> to get some cool dependency graphs and help during refactoring.</p>
<p>By requiring individual methods you discourage the use of too many dependencies, which also have the added bonus of smaller source files and modules that take care of a single responsibility. I&#8217;ve been doing that for the past year with <a href="http://millermedeiros.github.com/amd-utils/">amd-utils</a> and it&#8217;s working great. </p>
<p>Of course there should be a way to require the whole package at once for brevity:</p>
<pre class="brush:js">
// load whole jQuery package
require('jquery');
// or individual modules
require('jquery/dom');
require('jquery/css');
require('jquery/ajax');
</pre>
<p>Lazy users could still be lazy but would allow the <em>freaks</em> to control what they load and how they use it.</p>
<h3>The list goes on&#8230;</h3>
<p>I didn&#8217;t listed all the things, just the ones that bothers me more, but it should be enough to show that there are a lot of things to be improved and that lack of consistency is my main complaint. If you are a jQuery maintainer please consider a few of them for the future.</p>
<h3>VanillaJS &amp; Why I use jQuery</h3>
<p>Yes, for modern browsers jQuery isn&#8217;t so relevant but it is still nice to have better abstractions, it shields the app from browser discrepancies and increases productivity. Nicholas Zakas gets into more details on <a href="http://oreilly.com/javascript/radarreports/native-javascript-apis.csp">The Problem with Native JavaScript APIs</a>, worth a read.</p>
<p>jQuery is my library of choice for most projects (even if working by myself) mainly because it is popular. It&#8217;s easier to find someone to maintain/contribute, there are a lot of opensource plugins and components, bugs are spotted/fixed quickly since it&#8217;s being used by millions of sites, etc. It is also very productive after you get used to it&#8230;</p>
<p>I guess sometimes &#8220;worse&#8221; is really &#8220;better&#8221;.</p>
<h3>Further Reading</h3>
<ul>
<li><a href="http://blog.millermedeiros.com/stop-writing-plugins-start-writing-components/">Stop Writing Plugins</a></li>
<li><a href="http://blog.millermedeiros.com/avoiding-the-this-keyword-on-jquery/">Avoiding the this keyword on jQuery related code</a></li>
<li><a href="http://blog.millermedeiros.com/naming-methods-properties-and-objects/">Naming methods, properties and objects</a></li>
<li><a href="http://www.jwz.org/doc/worse-is-better.html">The rise of &#8220;worse is better&#8221;</a> <small>(external)</small></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/jquery-wish-list/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Travis CI : Continuous Integration Made Easy</title>
		<link>http://blog.millermedeiros.com/travis-ci/</link>
		<comments>http://blog.millermedeiros.com/travis-ci/#comments</comments>
		<pubDate>Mon, 10 Dec 2012 13:32:22 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[best practices]]></category>
		<category><![CDATA[build]]></category>
		<category><![CDATA[continuous integration]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[opensource]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1596</guid>
		<description><![CDATA[This weekend I spent some time improving the structure of some of my open source projects repositories and also finally decided to add a Travis-ci hook to the most active/newest ones. Travis is a free continuous integration server for open source projects that can be used to automate tests and help you deal with projects [...]]]></description>
				<content:encoded><![CDATA[<p><img src="http://blog.millermedeiros.com/wp-content/uploads/2012/12/travis.png" alt="" title="travis" width="165" height="105" class="alignleft noScale size-full wp-image-1597" /> This weekend I spent some time improving the structure of some of my open source projects repositories and also finally decided to add a Travis-ci hook to the most active/newest ones.</p>
<p>Travis is a free <a href="http://en.wikipedia.org/wiki/Continuous_integration">continuous integration</a> server for open source projects that can be used to automate tests and help you deal with projects that have multiple contributors. If you are familiar with GitHub you probably seen their build status icons on a few projects before <small>(on the image above)</small>. It can be used to test multiple languages like JavaScript, PHP, Python, Ruby, Java and many others.  It also have options to notify the project maintainers every time the build status changes or on each commit. <small>(email, IRC, campfire, etc)</small></p>
<p>It is really easy to setup it if your tests are already executed on the command line. If the tests needs a browser to work you can hook a headless browser like <a href="http://phantomjs.org/">PhantomJS</a>. <small>- For my projects I&#8217;m just executing the tests on node.js for now since that should be enough to catch most errors. -</small> Having a headless browser can help to double check if the code works on multiple environments.</p>
<p>Travis documentation is very clear and the amount of boilerplate is minimal, for a regular node.js project you just need a file named <code>.travis.yml</code> on the root folder containing:</p>
<pre class="brush:js">
 language: node_js
 node_js: 0.8
</pre>
<p><span id="more-1596"></span></p>
<p>By default it will execute the <code>npm test</code> script for node.js projects. If you want/need you can execute multiple scripts like:</p>
<pre class="brush:js">
 script:
   - "echo Travis rocks"
   - "node build"
   - "npm test"
</pre>
<p>On <a href="http://millermedeiros.github.com/amd-utils/">amd-utils</a> I added a pretest script that checks if all modules have specs <small>(if it can&#8217;t find it will create a failing spec for the module)</small> and update all packages/spec runner. I also added a script to check the code coverage of my tests (using <a href="https://github.com/yahoo/istanbul/">Istanbul</a>) to make sure pull requests <small>(and my own commits)</small> have a high code coverage.</p>
<pre class="brush:js">
 script:
   - "npm test --coverage"
   - "node ./node_modules/.bin/istanbul check-coverage --statements 90 --branches 90 --lines 90 --functions 90"
</pre>
<p>With the code above the integration test will fail if the code coverage is below 90%. This will ensure we have tests for every method and will help check if our tests are covering different scenarios <small>- code coverage is just a metric to help you identify potential problems, it doesn&#8217;t really mean your tests are good enough, it just identify if the statement/line/function/branch was executed at least once, so beware, don&#8217;t trust it blindly. -</small> I&#8217;m not setting the code coverage higher since amd-utils have some specific code branches that are only executed on old JS engines <small>(specially IE)</small>. Check the <a href="https://travis-ci.org/millermedeiros/amd-utils">last build report</a>.</p>
<p>Travis is nicely integrated with Github, showing if a pull request passes the CI test, it is a good way to spot errors early.</p>
<p><img src="http://blog.millermedeiros.com/wp-content/uploads/2012/12/tavis_pull_request.png" alt="" title="tavis_pull_request" width="550" height="411" class="alignnone size-full wp-image-1600" /></p>
<p>The build status icon <img src="https://secure.travis-ci.org/millermedeiros/js-signals.png?branch=master" alt="" /> is also a nice indicator to add to the project README.md file.</p>
<p>I highly recommend it for projects with multiple contributors, will be using it on <em>all</em> open source projects from now on.</p>
<p>Automate repetitive tasks and make contribution easier, it will surely pay off in the long run.</p>
<h3>Further Reading</h3>
<ul>
<li><a href="https://travis-ci.org/">Travis CI homepage</a> <small>(external)</small></li>
<li><a href="http://about.travis-ci.org/docs/">Travis CI Documentation</a> <small>(external)</small></li>
<li><a href="http://ariya.ofilabs.com/2012/12/quality-code-via-multiple-layers-of-defense.html">Quality Code via Multiple Layers of Defense</a> <small>(external)</small></li>
<li><a href="http://ariya.ofilabs.com/2012/12/javascript-code-coverage-with-istanbul.html">JavaScript Code Coverage with Istanbul</a> <small>(external)</small></li>
<li><a href="http://blog.millermedeiros.com/node-js-protip-avoid-global-test-runners/">Node.js Protip: Avoid Global Test Runners</a></li>
<li><a href="http://blog.millermedeiros.com/node-js-as-a-build-script/">Node.js as a Build Script</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/travis-ci/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>esformatter &amp; rocambole</title>
		<link>http://blog.millermedeiros.com/esformatter-rocambole/</link>
		<comments>http://blog.millermedeiros.com/esformatter-rocambole/#comments</comments>
		<pubDate>Fri, 07 Dec 2012 14:15:20 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ast]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[opensource]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1589</guid>
		<description><![CDATA[Yesterday I pushed 2 new projects to github, was unsure if I was going to do it since maintaining opensource projects can demand a lot of time but heck, I&#8217;m looking for contributors and they can be useful to more people, so why not? I used editors/IDEs that had a good code formatter for a [...]]]></description>
				<content:encoded><![CDATA[<p><img src="http://blog.millermedeiros.com/wp-content/uploads/2012/12/rocambole.jpg" alt="" title="rocambole" width="630" height="467" class="alignnone size-full wp-image-1592" /></p>
<p>Yesterday I pushed 2 new projects to github, was unsure if I was going to do it since maintaining opensource projects can demand a lot of time but heck, I&#8217;m looking for contributors and they can be useful to more people, so why not?</p>
<p>I used editors/IDEs that had a good code formatter for a while and ever since I started doing more JavaScript development I missed a code formatter as powerful/flexible as <a href="http://fdt.powerflasher.com/docs/Advanced_code_formatter_%28AS3_%2B_MXML%29">FDT</a>. I know <a href="http://www.jetbrains.com/webstorm/webhelp/code-style-javascript.html">WebStorm</a> has a very good support for JavaScript but nowadays I&#8217;m a Vim user and it&#8217;s really hard to make the switch. I wish I could have the same amount of settings on a command-line tool, that way it could be hooked into multiple text editors <small>(Vim, Emacs, SublimeText, Cloud9, etc&#8230;)</small>, have an external configuration file <small>(so it could be shared between team members)</small> and used to batch-process files. Being written in JavaScript would also be a plus <small>(so it could be used inside the browser and have more contributors)</small>.</p>
<p><span id="more-1589"></span></p>
<p>At the beginning of 2012 I decided to look for tools that accomplished what I wanted but couldn&#8217;t find anything that was even close <small>(<a href="http://jsbeautifier.org/">jsbeautifier</a> is not enough)</small>, so I submitted a feature request to <a href="https://github.com/Constellation/escodegen/issues/4">escodegen</a>, given that it had a good structure and was being actively maintained, I thought it could be a strong candidate. The months passed by and I didn&#8217;t had time to contribute to it <small>(and forgot about)</small>, but most importantly, my opinion did change. &#8211; Nowadays I believe that a reliable code formatter should not rewrite the original source code, it should only modify the white spaces and line breaks while keeping all the original tokens <small>(only non-destructive transformations)</small>. I also fell that it would increase escodegen complexity a lot and it is beyond the responsibility of the project <small>(generate JavaScript from an AST).</small></p>
<p>During the process I tried to use <a href="https://github.com/substack/node-falafel">node-falafel</a> to traverse &amp; modify the AST but it didn&#8217;t work as I needed &#8211; recursive walk started from root node and some nodes was traversed more than once &#8211; and it also didn&#8217;t had any information about original tokens, so I created a separate project to do the AST <em>walk</em> and manipulation. It&#8217;s called <strong>Rocambole</strong> &#8211; inspired by a <a href="https://www.google.com.br/search?q=rocambole">popular Brazilian cake</a> and also by node-falafel and node-burrito (rocambole is a <em>sweet wrap</em>).</p>
<p>Check both projects on Github and use the issue tracker for feature requests, questions and bugs:</p>
<ul>
<li><a href="https://github.com/millermedeiros/esformatter/">esformatter</a></li>
<li><a href="https://github.com/millermedeiros/rocambole/">rocambole</a></li>
</ul>
<p>Contributors are always welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/esformatter-rocambole/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Why I favor while loops</title>
		<link>http://blog.millermedeiros.com/why-i-favor-while-loops/</link>
		<comments>http://blog.millermedeiros.com/why-i-favor-while-loops/#comments</comments>
		<pubDate>Mon, 03 Dec 2012 05:00:05 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[random thoughts]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1491</guid>
		<description><![CDATA[I remember that my first contact with programming loops was through the for statement and I used it almost exclusively for many years. I&#8217;ll explain why I&#8217;ve been favoring while loops over for loops in the past couple years. Beware that this is only my personal preference and the reasoning behind it are very subjective. [...]]]></description>
				<content:encoded><![CDATA[<p>I remember that my first contact with <em>programming loops</em> was through the <code>for</code> statement and I used it almost exclusively for many years. I&#8217;ll explain why I&#8217;ve been favoring <code>while</code> loops over <code>for</code> loops in the past couple years.  Beware that this is only <strong>my personal preference</strong> and the reasoning behind it are very subjective. <strong>Use what works better for you.</strong></p>
<p><strong>TL;DR:</strong> <code>while</code> is less verbose and more <em>clear</em> in many cases.</p>
<p><span id="more-1491"></span></p>
<h3>Less <em>tokens</em> per line</h3>
<p>Lets take a very basic example into consideration:</p>
<pre class="brush:js; gutter:false">
for(var i = 0; i &lt; 100; i++) {
    console.log(i);
}
</pre>
<p>Converted into a <code>while</code> loop:</p>
<pre class="brush:js; gutter:false">
var i = -1;
while(++i &lt; 100) {
    console.log(i);
}
</pre>
<p>What bothers me more on the <code>for</code> statement is that you have too many things going on the same line. Variable declaration, conditional logic and another expression to increment the variable. I find the line <code>while(++i &lt; 100)</code> way easier to read/understand than <code>for(var i = 0; i &lt; 100; i++)</code>, less tokens to grok and a single responsibility.</p>
<p>Another benefit that I see by moving the <code>var</code> declaration to outside the loop logic is that it makes it clear that variables aren&#8217;t bound to the loop scope <small>(JavaScript only have block scope if you use the <code>let</code> keyword which isn&#8217;t standard).</small> If you are enforcing manual variable hoisting and/or single <code>var</code> statement on your code guidelines the <code>while</code> loop will make even more sense.</p>
<h3>Many operations can be executed in reverse order</h3>
<p>Many types of operations can be executed in reverse order without affecting the end result. <code>while</code> loops are very succinct and <em>clear</em> when looping backwards:</p>
<pre class="brush:js; gutter:false">
var n = 100;
while (n--) {
    console.log(n);
}
</pre>
<p>Compared to a <code>for</code> loop that does the same:</p>
<pre class="brush:js; gutter:false">
for(var n = 99; n &gt;= 0; n--) {
    console.log(n);
}
</pre>
<p>Notice that on the <code>for</code> loop you need to subtract <code>1</code> from the <code>length</code> to achieve same result <small>(array indexes starts at zero)</small>.</p>
<p><small> PS: Some operations are <em>slightly</em> faster when executed in reverse since they avoid changing the size of the Array during the operations. (change it only once upfront) </small></p>
<h3>Processing Array elements</h3>
<p>It is very common to use <code>for</code>/<code>while</code> loops to process array items. It&#8217;s a common knowledge that we should avoid property lookups whenever possible to increase performance, so it&#8217;s a very common practice to cache the <code>Array.length</code>. By doing that the <code>for</code> declaration gets even more complex:</p>
<pre class="brush:js; gutter:false">
for(var i = 0, n = arr.length; i &lt; n; i++) {
    console.log(arr[i]);
}
</pre>
<p>I would rather write it like this:</p>
<pre class="brush:js; gutter:false">
var i = -1,
    n = arr.length;
while (++i &lt; n) {
    console.log(arr[i]);
}
</pre>
<p>Each line takes care of a single responsibility, less lines of code isn&#8217;t always a good thing.</p>
<p>If you are <strong>100% sure</strong> that the array won&#8217;t contain <em>falsy</em> values (<code>null</code>, <code>undefined</code>, <code>0</code>, <code>false</code>, <code>""</code>) you could make it even simpler:</p>
<pre class="brush:js; gutter:false">
/* jshint boss:true */
var cur, i = 0;
while (cur = arr[i++]) {
    console.log(cur);
}
</pre>
<p>Beware that <em>falsy</em> values will break the loop, use with care.</p>
<p><small>PS: I&#8217;ve been favoring <code>Array#forEach</code>, <code>Array#map</code>, <code>Array#filter</code> in many cases since I think it focus the program code on the actual problem and not the loop logic, but I still use plain loops in some cases to iterate over arrays.</small></p>
<h3>RegExp.exec</h3>
<p>The same pattern above could be used for methods like <code>RegExp#exec</code>:</p>
<pre class="brush:js; gutter:false">
var re = /\w+/g,
    match;
while (match = re.exec('== Lorem ipsum dolor sit amet ==')) {
    console.log(match);
}
</pre>
<p>This will execute the <code>RegExp#exec</code> method over the whole string until it can&#8217;t find anything that matches the pattern. It can simplify parsing logic a lot.</p>
<h3>Getting &#8220;clever&#8221;</h3>
<p>I&#8217;ve seen lots of people abusing the fact that you can omit the expressions on the <code>for</code> loop or that you can use the <a href="http://javascriptweblog.wordpress.com/2011/04/04/the-javascript-comma-operator/">comma operator to do tricky things</a>, but why not use the <code>while</code> statement instead?</p>
<pre class="brush:js; gutter:false">
// first and last expressions are optional
var i = 0, cur;
for( ; cur = arr[i++]; ) {
    // ...
}
</pre>
<p>By (ab)using the comma operator you can basically remove all the work from the <code>while</code> body and move it to the expression block.</p>
<pre class="brush:js; gutter:false">
// will execute until `cur` is falsy and/or `cur.doSomething()` retuns
// a falsy value
var i = 0, cur;
while( cur = arr[i++], cur &amp;&amp; cur.doSomething() );
</pre>
<p>You can find a real working example of this concept applied to a very small snippet on the <a href="https://gist.github.com/527683">IE version detection script</a> by padolsey and friends. I also use <a href="https://github.com/millermedeiros/js-signals/blob/71bdf73ba6891b98f7701e9e3273f320860922c2/dist/signals.js#L369-371">something similar on js-signals</a> to execute all bindings of a signal until one of them stops the propagation <small>(without the comma operator).</small></p>
<p>I&#8217;m not a fan of very <em>clever</em> tricks since I think they usually makes code harder to understand, but it is very good to know when/how to use these techniques since they can open your mind to simpler solutions in some cases.</p>
<h3>Bonus: do-while</h3>
<p><code>do-while</code> is one of these features that I rarely need, but in some cases it can be useful. On a <a href="http://mountaindew.com">recent project</a> I needed a greedy algorithm to search for the next empty cell on a grid that wasn&#8217;t adjacent to a similar item <small>(couldn&#8217;t place product bottles next to each other before user starts filtering the grid items)</small>, the <em>easiest</em> way to solve it was to write a <code>do-while</code>:</p>
<pre class="brush:js; gutter:false">
do {
    // get next empty cell that can fit item
    cellIdx = this._getFitIndex(item, rowIdx, cellIdx);
    // check if cell isn't adjacent to a similar item (on current &amp; prev rows)
    allowPlacement = this._checkPlacement(item, rowIdx, cellIdx);
} while (!allowPlacement &amp;&amp; cellIdx !== -1);
</pre>
<p>After the loop I just had to check if <code>allowPlacement &amp;&amp; cellIdx !== -1</code> and place the item at that index. If <code>false</code> I created a new row on the grid and repeated the process.</p>
<p>On js-signals I use a <code>do-while</code> to implement a very <a href="https://github.com/millermedeiros/js-signals/blob/71bdf73ba6891b98f7701e9e3273f320860922c2/dist/signals.js#L242-247">simple sorted insert</a>.</p>
<p>The <code>do-while</code> is nothing more than a sugared version of a <code>while(true)</code> which means I could totally live without it as well.</p>
<pre class="brush:js; gutter:false">
// same as previous example
while(true){
    cellIdx = this._getFitIndex(item, rowIdx, cellIdx);
    allowPlacement = this._checkPlacement(item, rowIdx, cellIdx);
    if ((allowPlacement &#038;&#038; cellIdx !== -1) || cellIdx === -1) break;
}
</pre>
<h3>top-level iterators</h3>
<p>I&#8217;ve been using <a href="http://moutjs.com">mout</a> on almost all my projects for the past year and it is really great to access the <code>array</code> and <code>object</code> iterators as top-level functions:</p>
<pre class="brush:js; gutter:false">
var forEach = require('mout/array/forEach');
forEach(arr, function(item, i){
   console.log(i, item);
});
</pre>
<p>It would be <em>nice</em> if JavaScript had some kind of sugar for this kind of loops (since they are so common), maybe something that doesn&#8217;t need all the <code>function</code> boilerplate and that works over array and objects <small>(anything that is iterable)</small>, I would probably suggest a syntax like this:</p>
<pre class="brush:js; gutter:false">
// sugar for Array#forEach and Object#forOwn
each(arr as [item, i]) {
  console.log(i, item);
}
</pre>
<p>On <em>Harmony</em> there is a proposal for the <a href="http://wiki.ecmascript.org/doku.php?id=harmony:iterators"><code>for of</code> iterator</a>, which is very similar:</p>
<pre class="brush:js; gutter:false">
// unsure if on Array we can also get the index
for(item of arr) {
  console.log(item);
}
</pre>
<p>If I was designing a language I would definitely include a feature like that, loops should have the least amount of boilerplate/distraction/landmines as possible.</p>
<h3>Conclusion</h3>
<p>I will probably avoid <code>for</code> loops on my own projects for the foreseeable future. <code>while</code> loops and ES5-like Array methods FTW <small>(map, reduce, forEach, &#8230;)</small></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/why-i-favor-while-loops/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>nodefy: convert AMD modules to node.js</title>
		<link>http://blog.millermedeiros.com/nodefy-convert-amd-modules-to-node-js/</link>
		<comments>http://blog.millermedeiros.com/nodefy-convert-amd-modules-to-node-js/#comments</comments>
		<pubDate>Wed, 21 Nov 2012 15:48:13 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[amd]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[opensource]]></category>
		<category><![CDATA[resources]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1579</guid>
		<description><![CDATA[I&#8217;ve been using amd-utils on almost all my projects and sometimes I find myself wanting to use some of the methods on my node.js programs as well, so I decided to write a tool to convert the modules automatically. The tool uses Esprima internally so it will keep the indentation, comments and it should work [...]]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve been using <a href="http://millermedeiros.github.com/amd-utils/">amd-utils</a> on almost all my projects and sometimes I find myself wanting to use some of the methods on my node.js programs as well, so I decided to write a tool to convert the modules automatically.</p>
<p>The tool uses <a href="http://esprima.org">Esprima</a> internally so it will keep the indentation, comments and it should work as long as the code can be parsed by Esprima. It will do as few replacements as possible to avoid undesired side effects.</p>
<p>Check the <a href="https://github.com/millermedeiros/nodefy">project repository</a> for more info and please use the <a href="https://github.com/millermedeiros/nodefy/issues">issue tracker</a> for feature requests, bug reports and questions/feedback.</p>
<h3>Related</h3>
<ul>
<li><a href="http://blog.millermedeiros.com/namespaces-are-old-school/">Namespaces are old school</a></li>
<li><a href="http://blog.millermedeiros.com/amd-is-better-for-the-web-than-commonjs-modules/">AMD is better for the web than CommonJS modules</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/nodefy-convert-amd-modules-to-node-js/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Avoiding the this keyword on jQuery related code</title>
		<link>http://blog.millermedeiros.com/avoiding-the-this-keyword-on-jquery/</link>
		<comments>http://blog.millermedeiros.com/avoiding-the-this-keyword-on-jquery/#comments</comments>
		<pubDate>Fri, 09 Nov 2012 21:51:28 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[best practices]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1560</guid>
		<description><![CDATA[jQuery implements some nice abstractions for DOM manipulation and browser events, removing a lot of crossbrowser issues and making it easier to accomplish non-trivial tasks. - it also has drawbacks and some poor design decisions, but I will leave that for another post. Maybe one day I will write my jQuery 2.0 wishlist&#8230; - Today [...]]]></description>
				<content:encoded><![CDATA[<p>jQuery implements some nice abstractions for DOM manipulation and browser events, removing a lot of crossbrowser issues and making it easier to accomplish <em>non-trivial</em> tasks. <small>- it also has drawbacks and some poor design decisions, but I will leave that for another post. Maybe one day I will write my jQuery 2.0 wishlist&#8230; -</small> Today I will explain why I usually avoid using the <em>magic</em> <code>this</code> keyword inside event handlers and inside most methods that manipulates jQuery collections.</p>
<p><span id="more-1560"></span></p>
<h3>The <code>this</code> keyword</h3>
<p>The fact that you can call a method and pass a different context, by using <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply">Function#apply</a> and <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call">Function#call</a>, is one of the most powerful things for code reuse and also one of the most misunderstood features in JavaScript. jQuery (ab)uses this feature a lot, which in my <small>(not so humble)</small> opinion is not a very good design decision.</p>
<h3>Newbies and code reuse</h3>
<p>It is confusing for newbies and it favors code that is tight coupled with a specific scenario, the chance of reusing the same method latter is reduced.</p>
<h3>Ambiguity and hidden dependency</h3>
<p>The <code>this</code> keyword is too ambiguous, which makes the code harder to understand, you need to check how the method is invoked to understand what value <code>this</code> holds.</p>
<pre class="brush:js">
function injectMoreInfoLink(i){
    $(this).append('&lt;a href="#/foo/'+ i +'"&gt;More Info&lt;/a&gt;');
}
$('.foo').each(injectMoreInfoLink);
</pre>
<p>If you use an IDE/editor which gives some sort of code completion based on the parameters that the method accepts you wouldn&#8217;t know that you need to invoke the <code>injectMoreInfoLink</code> function as <code>injectMoreInfoLink.call(element, i)</code>. Very counterintuitive. List all dependencies and avoid <em>magic</em>, it is going to be way easier to understand and reuse it in the future:</p>
<pre class="brush:js">
function injectMoreInfoLink(i, target){
    $(target).append('&lt;a href="#/foo/'+ i +'"&gt;More Info&lt;/a&gt;');
}
// works exactly the same way as previous example
$('.foo').each(injectMoreInfoLink);
// you can call it easily if needed
injectMoreInfoLink(12, someElement);
</pre>
<p>PS: jQuery got the arguments order <em>wrong</em> on the <code>map</code> and <code>each</code> callbacks. On the ES5 Array methods the arguments order is reversed (value comes before index). This always drives me crazy and the main reason why I usually don&#8217;t use the static versions of <code>map</code> and <code>each</code> to iterate over arrays.</p>
<h3>Event Listeners, testability and bad practices</h3>
<p>I strongly believe that the abuse of the <code>this</code> keyword influences bad practices, since it&#8217;s easier to do it the <em>wrong</em> way.</p>
<p>Just to point out how the <code>this</code> keyword works inside jQuery event listeners:</p>
<pre class="brush:js">
// the same behavior applies if using event delegation
$('.btn').on('click', function(evt){
    // target can be a child of ".btn" or ".btn" itself
    console.log(this === evt.target); // true or false
    // currentTarget is the ".btn" itself
    console.log(this === evt.currentTarget); // true
});
</pre>
<p>A common pattern:</p>
<pre class="brush:js">
function Foo(name){
    this.name = name;
    $('.bar').click(this.doAwesomeStuffOnClick);
}
Foo.prototype = {
    doAwesomeStuffOnClick : function(evt){
        evt.preventDefault();
        // misleading, unsure if `this` is the instance or an element
        $(this).toggleClass('awesome');
        // ops, won't work as expected
        // how do you access the instance name ??
        console.log(this.name); // undefined
    }
};
var myObj = new Foo('lorem ipsum');
</pre>
<p>Another option is to create a local var <code>self</code> and inline the <code>doAwesomeStuffOnClick</code> method <small>- on this naive example that would work -</small> but I would rather avoid this kind of pattern, it leads to code that is harder to maintain/reuse/test. Sooner than you expect you will have 5 nested functions and a huge pile of spaghetti code <small>- been there, done that, no thanks.</small></p>
<pre class="brush:js">
function Foo(name){
    this.name = name;
    // this is an anti-pattern, avoid it as much as possible !!!
    var self = this;
    $('.bar').click(function(evt){
        evt.preventDefault();
        $(this).toggleClass('awesome');
        console.log(self.name);
    });
}
var myObj = new Foo('lorem ipsum');
</pre>
<p>I would probably implement it like this:</p>
<pre class="brush:js">
function Foo(name){
    this.name = name;
    // override method and bind to proper context
    this.doAwesomeStuffOnEvent = $.proxy(this.doAwesomeStuffOnEvent, this);
    $('.bar').click(this.doAwesomeStuffOnEvent);
}
// all methods are grouped on the prototype
// can be reused/tested/overwritten individually
Foo.prototype = {
    doAwesomeStuffOnEvent : function(evt){
        evt.preventDefault();
        this.doAwesomeStuff(evt.currentTarget);
    },
    doAwesomeStuff : function(target){
        $(target).toggleClass('awesome');
        console.log(this.name);
    }
};
var myObj = new Foo('lorem ipsum');
</pre>
<p>For most cases that might be overkill, but I&#8217;d rather code something that is easy to change than have to deal with a huge pile of mess, requirements change way more often than we expect.</p>
<p>More lines of code is not always a bad thing. If I ever need to execute the <code>doAwesomeStuff</code> on a different event type, let&#8217;s say a <code>keypress</code>, just need to add the new listener. If I decide to <em>subclass</em> this object I can override each individual method. That way you can also trigger <code>doAwesomeStuff</code> without passing an <code>Event</code> object, which depending on the scenario is a huge win. This also improves the testability of the code since every single concern is split into small chunks that can be called individually &#8211; unit testing FTW.</p>
<h3>Too much <code>this</code></h3>
<p>I&#8217;m not a huge fan of plugins, in fact I think <a href="http://blog.millermedeiros.com/stop-writing-plugins-start-writing-components/">most people should not be writing plugins at all</a>. If the <code>this</code> keyword is already confusing inside a simple code snippet, now think about a jQuery plugin.</p>
<pre class="brush:js">
// WARNING!! this code is useless and a very bad example of a plugin.
// we don't really need that many nested functions, it's just to point how
// confusing it can be to track what the `this` keyword means inside each fn
// PS: I've seen code like this many times
jQuery.fn.doFoo = function(className){
    // `this` points to the jQuery collection that was matched before calling
    // the `doFoo` method
    this.each(function(){
        // `this` is an individual element of the jQuery collection
        $(this).find(className).each(function(){
            // `this` is an individual element child of the collection
            $(this).append('bar');
        });
    });
    // we return the original collection so the user can "chain" multiple calls
    return this;
};
// FYI: it could be rewritten as `this.find(className).apend('bar');`
</pre>
<p>It can get even more confusing, now imagine a junior developer trying to debug or tweak this code&#8230; <small>#chaos</small></p>
<h3>Conclusion</h3>
<p>Be explicit whenever possible, more lines of code and longer variable names aren&#8217;t always a bad thing, code completion/snippets are here to help, it usually pays-off in the long run. Code should be easy to read by humans, typing <em>in most cases</em> isn&#8217;t the bottleneck.</p>
<h3>Further reading</h3>
<ul>
<li><a href="http://blog.millermedeiros.com/stop-writing-plugins-start-writing-components/">Stop writing plugins, start writing components</a></li>
<li><a href="http://blog.millermedeiros.com/keep-your-modules-and-functions-small/">Keep your modules and functions small</a></li>
<li><a href="http://blog.millermedeiros.com/a-case-against-private-variables-and-functions-in-javascript/">A case against private variables and functions in JavaScript</a></li>
<li><a href="https://gist.github.com/4135065">Naming this in nested functions</a> <small>(external)</small></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/avoiding-the-this-keyword-on-jquery/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Node.js Protip: Avoid Global Test Runners</title>
		<link>http://blog.millermedeiros.com/node-js-protip-avoid-global-test-runners/</link>
		<comments>http://blog.millermedeiros.com/node-js-protip-avoid-global-test-runners/#comments</comments>
		<pubDate>Mon, 29 Oct 2012 18:36:56 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[best practices]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[protip]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1540</guid>
		<description><![CDATA[Some of the most popular Node.js test frameworks advertise that they should be installed globally: Jasmine, Mocha, Buster.js, etc&#8230; I consider this an anti-pattern. am I the only one who find it &#8220;weird&#8221; that all (popular) node.js test frameworks uses a global install? &#8212; Miller Medeiros (@millermedeiros) October 25, 2012 On this post I will [...]]]></description>
				<content:encoded><![CDATA[<p>Some of the most popular Node.js test frameworks advertise that they should be installed globally: <a href="https://github.com/mhevery/jasmine-node">Jasmine</a>, <a href="http://visionmedia.github.com/mocha/">Mocha</a>, <a href="http://docs.busterjs.org/en/latest/">Buster.js</a>, etc&#8230; I consider this an anti-pattern.</p>
<blockquote class="twitter-tweet"><p>am I the only one who find it &#8220;weird&#8221; that all (popular) node.js test frameworks uses a global install?</p>
<p>&mdash; Miller Medeiros (@millermedeiros) <a href="https://twitter.com/millermedeiros/status/261545951406202880" data-datetime="2012-10-25T19:13:08+00:00">October 25, 2012</a></p></blockquote>
<p><script src="//platform.twitter.com/widgets.js" charset="utf-8"></script></p>
<p>On this post I will try to explain why it&#8217;s an anti-pattern and show how to avoid global installs by using <code>npm test</code> instead.</p>
<p><span id="more-1540"></span></p>
<h3>Globals are evil!</h3>
<p><em>Everybody</em> knows that global variables are evil, but somehow nobody been talking about global installs of tools that doesn&#8217;t need to be installed globally to work. Very few Node.js modules should be installed globally, probably only tools like <a href="https://github.com/jshint/node-jshint">jshint</a> <small>(which can be used by text editors/IDEs)</small> or anything that you expect to use together with other shell commands <small>(ie. file system related tools).</small> If your project depends on some third party code to work (including your tests) <strong>always favor local installs</strong>.</p>
<p>Local dependencies can be listed on the <code>package.json</code> file, so you keep track of the version, you can also commit them together with the project source code (making it easier for other devs to clone your project). It will reduce version conflicts and surely save you some headaches like &#8220;why do the tests work on my machine but not in others?&#8221;, which might be caused by a version conflict on the test framework.</p>
<p>If every single tool is installed globally the chance of name collisions will get extremely high. Please don&#8217;t do it unless you <strong>really</strong> need it.</p>
<h3><code>npm test</code> is your savior</h3>
<p>Besides the fact of NPM being an awesome package manager it also has the very neat feature called <a href="https://npmjs.org/doc/scripts.html">scripts</a>. It allows custom hooks to be executed before/after/during a certain action and comes with some good default behavior.</p>
<p>You probably want to run the tests multiple times and probably with the same arguments, so it&#8217;s way better to keep the test information inside the <code>package.json</code> file and reference the local <code>bin</code> file:</p>
<pre class="brush:js">
{
    "name" : "example",
    "version" : "1.0.0",
    "devDependencies" : {
        "jasmine-node" : "~1.0.26"
    },
    "scripts" : {
        "test" : "node node_modules/jasmine-node/bin/jasmine-node spec"
    }
}
</pre>
<p>Now you can run <code>npm install --dev</code> to install the <code>devDependencies</code> and every time you run <code>npm test</code>, it will execute the <code>node node_modules/jasmine-node/bin/jasmine-node spec</code> command, simple like that.</p>
<p>Automate ALL the things and avoid globals for a <em>saner life</em>.</p>
<h3>Further Reading</h3>
<ul>
<li><a href="http://www.devthought.com/2012/02/17/npm-tricks/">NPM Tricks</a></li>
<li><a href="http://package.json.jit.su/">package.json: An Interactive Guide</a></li>
<li><a href="http://www.mikealrogers.com/posts/nodemodules-in-git.html">node_modules in git</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/node-js-protip-avoid-global-test-runners/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  blog.millermedeiros.com/feed/ ) in 0.40528 seconds, on May 22nd, 2013 at 9:40 pm UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on May 22nd, 2013 at 10:40 pm UTC -->
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<!-- Quick Cache Is Fully Functional :-) ... A Quick Cache file was just served for (  blog.millermedeiros.com/feed/ ) in 0.00033 seconds, on May 22nd, 2013 at 10:13 pm UTC. -->