<?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>Wed, 09 May 2012 01:17:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>AMD-Utils: Math Utilities</title>
		<link>http://blog.millermedeiros.com/amd-utils-math-utilities/</link>
		<comments>http://blog.millermedeiros.com/amd-utils-math-utilities/#comments</comments>
		<pubDate>Sat, 25 Feb 2012 06:52:39 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1448</guid>
		<description><![CDATA[This post was going to be about the Math utilities present on AMD-Utils. Some of them are essential to my day-to-day work and simplify the code structure a lot. I was going to explain how to use them (which is very easy) but most importantly, why they are useful and when to use them. But [...]]]></description>
			<content:encoded><![CDATA[<p>This post was going to be about the Math utilities present on <a href="http://millermedeiros.github.com/amd-utils/">AMD-Utils</a>. Some of them are essential to my day-to-day work and simplify the code structure a lot.</p>
<p>I was going to explain how to use them <small>(which is very easy)</small> but most importantly, why they are useful and when to use them. But instead of publishing it as a post I decided to update the docs and add all the info there so everything is centralized.</p>
<p>I recommend that you try to understand these methods and which kind of problems they try to solve. They are all very trivial to implement but of an extreme usefulness depending on the kind of project you are building. I also think that some of them changed the way I approach some kinds of problems. I use them so much that it&#8217;s hard to imagine coding something complex without something similar <small>(I coded the methods clamp/loop/lerp/norm a million times).</small></p>
<p>So jump over to the docs and understand how to (ab)use these helpers. Even if you are not using amd-utils you can check the source code and implement it by yourself or extract the methods. Most of them are common knowledge but I feel that not that many people know how to use them properly or outside of the regular context, that&#8217;s why I thought some explanation would be helpful.</p>
<p>Docs: <a href="http://millermedeiros.github.com/amd-utils/math.html">http://millermedeiros.github.com/amd-utils/math.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/amd-utils-math-utilities/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Keep your modules and functions small</title>
		<link>http://blog.millermedeiros.com/keep-your-modules-and-functions-small/</link>
		<comments>http://blog.millermedeiros.com/keep-your-modules-and-functions-small/#comments</comments>
		<pubDate>Sat, 04 Feb 2012 03:01:48 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[best practices]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1433</guid>
		<description><![CDATA[This post is about a very simple thing that I&#8217;ve been doing since I started to code (by coincidence) and that I feel that increases a lot the readability and organization of my code. Some people may not agree with it but for me it makes total sense and was also documented by some experienced [...]]]></description>
			<content:encoded><![CDATA[<p>This post is about a very <em>simple</em> thing that I&#8217;ve been doing since I started to code <small>(by coincidence)</small> and that I feel that increases a lot the readability and organization of my code. Some people may not agree with it but for me it makes total sense and was also documented by some experienced developers like Uncle Bob on his great book <a href="http://books.google.com.br/books/about/Clean_code.html?id=dwSfGQAACAAJ">Clean Code</a>. I tend to think that a single approach may not be the best one for everybody <small>- since every person thinks on a different way -</small> but I&#8217;m pretty confident that this advise will be good to a lot of people and that it will increase the overall quality of the code.</p>
<p><strong>The rule is simple, split larger functions/classes into smaller specialized ones, period.</strong> It will not only increase the readability but it will also make the code more reusable since it will be easier to override the default behavior if needed <small>(especially if extending a class or reusing a 3rd party lib)</small>. I will try to explain how and give a basic example.</p>
<p><span id="more-1433"></span></p>
<h3>Why?</h3>
<p>Basically because smaller functions are easier to understand and smaller files are easier to read. Try to read a very large paragraph and you will see that the information is way harder to <em>grasp</em>.</p>
<p>Another huge benefit in keeping your classes/modules small is that there is a big chance that it will have a very high <a href="http://en.wikipedia.org/wiki/Cohesion_(computer_science)">cohesion</a> <small>(all functions are strongly-related)</small>, low cohesion is a very bad <em>code smell</em>. By grouping functions by context it will be very easy to identify which file should be edited and where. If the bug is on the &#8220;drop down menu&#8221; you should check the <code>DropDown</code> <em>class</em>, if you need to change the way files are written to the system than you should update the <code>fileWriter</code>, etc&#8230;</p>
<p>I&#8217;ve said it before and I&#8217;m going to say it again:</p>
<blockquote><p>
  Comments are usually a sign of poor/lazy/confusing implementations. (<a href="http://blog.millermedeiros.com/2011/03/inline-documentation-why-im-ditching-it/">source</a>)
</p></blockquote>
<p>By keeping your functions small and by using descriptive names you will reduce the amount of necessary comments a lot, <strong>a few lines of well written code can say more to a developer than many pages of documentation</strong> <small>(your mileage may vary)</small>. Don&#8217;t describe with comments what can be described with code!!</p>
<h3>How?</h3>
<p>Uncle Bob says that the <strong>optimal size of a functions is 1 line</strong>, and no, he is not talking about 1 line of mangled code with lots of chained methods, he is talking about 1 line of <em>clean code</em> that does one thing and does it well. It may seem drastic, but I must admit that it is a very good goal to keep in mind <small>(even if you don&#8217;t follow it by heart)</small>.</p>
<p>Let&#8217;s use a simple example to describe it, first some CSS:</p>
<pre class="brush:css">
.awsum {
    background-color: #0ff;
    position: absolute;
    width: 300px;
    height: 300px;
}
</pre>
<p>Now some JS code <small>(using jQuery for brevity)</small>:</p>
<pre class="brush:js">
//this whole example is an anti-pattern
function AwsumWidget(parent){
    this.root = $('&lt;div class="awsum"/&gt;');

    this.root
        .appendTo(parent)
        .fadeOut(0)
        .fadeIn(400)
        .click(function(evt){
            $(this).animate({
                top : Math.random() * 300,
                left : Math.random() * 300
            }, 500, 'swing');
        });
}

AwsumWidget.prototype = {

    remove : function(){
        if (! this.root) return;
        var self = this;
        this.root.fadeOut(400, function(){
            self.root.remove();
            delete self.root;
        });
    }

};
</pre>
<p>Now let&#8217;s suppose you need to create a <code>RadWidget</code>, it should have all the basic functionality from the <code>AwsumWidget</code> but it should do a different animation on click, how would you do it? Since all the logic is inside the constructor you will need to duplicate the code just to replace the click handler, not scalable/flexible at all&#8230; First step is to refactor <code>AwsumWidget</code> so it&#8217;s easier to extend it and overwrite just what we need, lets also abstract some hard-coded values to make it easier to update <small>- that&#8217;s also a very good practice, don&#8217;t leave &#8220;magic&#8221; numbers in the middle of the code, specially if you use it more than once, giving a name to the value will help describe what it does</small>:</p>
<pre class="brush:js">
var MAX_POS = 300,
    TRANSITION_DURATION = 400;

function AwsumWidget(parent){
    this._create(parent);
    this._animateIn();
    this._attachEvents();
}

AwsumWidget.prototype = {

    _html : '&lt;div class="awsum"/&gt;',

    _create : function(parent){
        this.root = $(this._html).appendTo(parent);
    },

    _attachEvents : function(){
        this.root.click(this._animateOnClick);
    },

    _animateOnClick : function(evt){
        $(this).animate({
            top : Math.random() * MAX_POS,
            left : Math.random() * MAX_POS
        }, TRANSITION_DURATION, 'swing');
    },

    _animateIn : function(){
        this.root.fadeOut(0).fadeIn(400);
    },

    remove : function(){
        if (! this.root) return;
        this._animateOut();
    },

    _animateOut : function(){
        this.root.fadeOut(TRANSITION_DURATION, $.proxy(this._destroy, this));
    },

    _destroy : function(){
        this.root.remove();
        delete this.root;
    }

};
</pre>
<p>It&#8217;s clearly more code, but by breaking the code into smaller specialized functions you can override just the functions you need and the function names already describe what the code is doing so it&#8217;s easy to follow the program logic, the <code>RadWidget</code> can be easily implemented as:</p>
<pre class="brush:js">
var MIN_SIZE = 50,
    MAX_SIZE = 300;

function RadWidget(){
    AwsumWidget.call(this);
    this.root.addClass('rad');
}

//let's just assume we are on an environment that supports Object.create
//https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create
RadWidget.prototype = Object.create(AwsumWidget.prototype);

RadWidget.prototype._animateOnClick = function(evt){
    var size = Math.max(Math.round(Math.random() * MAX_SIZE), MIN_SIZE);
    $(this).animate({
        width : size,
        height : size
    }, TRANSITION_DURATION, 'swing');
};
</pre>
<p>We reused all the code from the <code>AwsumWidget</code> and only changed the parts that we needed, that is the true power of breaking everything into separate functions, modular systems are more flexible by nature, since each part is treated as an individual <em>piece</em> you can replace them at will as long as you follow the proper interface.</p>
<h3>Sum Up</h3>
<p>Break your code into smaller pieces, it may seem more work but the benefits on the long run outweigh the initial overhead. And if you are thinking that it will slow down your code since you have more functions calls remember about the <a href="http://blog.millermedeiros.com/the-performance-dogma/">performance dogma</a>, unless you have a <strong>very large</strong> loop doing something trivial the extra function calls shouldn&#8217;t be the bottleneck. It is better to have a clean/organized structure and <em>tune</em> it if needed than to have a huge pile of mess and not being able to identify where the real bottleneck might be or react to new requirements on a timely fashion.</p>
<p>By breaking your code into smaller <em>blocks</em> it will also help you follow the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility Principle</a> which I consider one of the best advices about program structure.</p>
<p>Try it for a while, the more you do it the more natural it will fell and it&#8217;s really impressive how much it improves the code readability and reusability. It&#8217;s <em>very hard</em> to foresee all the needs and later on the road it might be harder to change it, so my advise is to refactor often and keep it as modular as possible. Make code easier for you and future developers to understand and maintain, it will pay-off sooner than you expect.</p>
<p>That&#8217;s it!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/keep-your-modules-and-functions-small/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Signal Emitter</title>
		<link>http://blog.millermedeiros.com/signal-emitter/</link>
		<comments>http://blog.millermedeiros.com/signal-emitter/#comments</comments>
		<pubDate>Mon, 16 Jan 2012 16:05:40 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[opensource]]></category>
		<category><![CDATA[resources]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1421</guid>
		<description><![CDATA[When I released JS-Signals I decided to create a document explaining the difference between different kinds of Observers and the possible pros and cons of each pattern, and as you can see on the document every approach has its pros/cons and depending on the scenario the recommended approach might change. Before coding JS-Signals I was [...]]]></description>
			<content:encoded><![CDATA[<p>When I released <a href="http://millermedeiros.github.com/js-signals/">JS-Signals</a> I decided to create a document explaining the <a href="https://github.com/millermedeiros/js-signals/wiki/Comparison-between-different-Observer-Pattern-implementations">difference between different kinds of Observers</a> and the possible pros and cons of each pattern, and as you can see on the document every approach has its pros/cons and depending on the scenario the recommended approach might change.</p>
<p>Before coding JS-Signals I was using a very basic EventEmitter &#8220;class&#8221; that could be used to listen/dispatch arbitrary events but ever since I released JS-Signals I almost didn&#8217;t used arbitrary events anymore <small>(because of the benefits of using a Signal),</small> but a couple weeks ago I had to propagate changes on my model classes to the UI and the changes are coming from many different inputs, so the easiest way to keep everything in sync was to dispatch events every time my model objects updated with a new value. In that case it is way easier to use a string ID for the event type than to create a new Signal object manually for each value, since the project was already using Signals everywhere I decided to code a simple EventEmitter that would use JS-Signals internal mechanism <small>(so I could use the advanced features if needed)</small> but still allow arbitrary event types.</p>
<p><span id="more-1421"></span></p>
<pre class="brush:js">
define(['signals'], function (signals) {

    /**
     * Signal Emitter
     * JS-Signals wrapper to convert it into a regular Event Emitter, which can
     * lister/dispatch arbitrary events.
     * @author Miller Medeiros
     * @version 0.1.1 (2012/01/23)
     * @license WTFPL
     */
    function SignalEmitter(){
        this._signals = {};
    }

    var _proto = SignalEmitter.prototype = {

        addListener : function(id, handler, scope, priority) {
            if (! this._signals[id]) {
                this._signals[id] = new signals.Signal();
            }
            return this._signals[id].add(handler, scope, priority);
        },

        removeListener : function(id, handler) {
            var sig = this._signals[id];
            if (! sig) return;
            sig.remove(handler);
        },

        getSignal : function(id) {
            return this._signals[id];
        },

        dispatch : function(id, args) {
            var sig = this._signals[id];
            if (! sig) return;
            if (args) {
                sig.dispatch.apply(sig, args);
            } else {
                sig.dispatch();
            }
        }

    };

    SignalEmitter.augment = function(target) {
        SignalEmitter.call(target);
        for (var key in _proto) {
            if (_proto.hasOwnProperty(key)) {
                target[key] = _proto[key];
            }
        }
    };

    return SignalEmitter;

});
</pre>
<p>You can use it as a standalone object:</p>
<pre class="brush:js">var obj = new SignalEmitter();
obj.addListener('foo', console.log, console);
obj.dispatch('foo', ['bar']);
</pre>
<p>Or extend an existing object to add the <code>SignalEmitter</code> behavior to it:</p>
<pre class="brush:js">var obj = {
    doSomething : function(args){
        this.dispatch('foo', ['lorem', 'ipsum']);
    }
};
//"inherit" from SignalEmitter object
SignalEmitter.augment(obj);

obj.addListener('foo', console.log, console);
obj.doSomething();
</pre>
<p>The method <code>addListener</code> returns a <a href="http://millermedeiros.github.com/js-signals/docs/symbols/signals.SignalBinding.html"><code>SignalBinding</code> object</a> and you can also get a reference to the underlaying <a href="http://millermedeiros.github.com/js-signals/docs/symbols/signals.Signal.html">Signal object</a> by calling <code>getSignal(id)</code> so you will have access to all the advanced features from JS-Signals while keeping a very flexible structure.</p>
<p>Feel free to remove unneeded features like <code>SignalEmitter.augment()</code> or <code>getSignal()</code>, added more as a reference and because on my current project I needed both things.</p>
<p>Very simple code but may be useful to somebody else&#8230;</p>
<p><strong>PS:</strong> please note that listening/dispatching non-existent events will fail silently <small>(one of the main reasons why I started using Signals)</small>, use with care.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/signal-emitter/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>A case against private variables and functions in JavaScript</title>
		<link>http://blog.millermedeiros.com/a-case-against-private-variables-and-functions-in-javascript/</link>
		<comments>http://blog.millermedeiros.com/a-case-against-private-variables-and-functions-in-javascript/#comments</comments>
		<pubDate>Thu, 12 Jan 2012 04:26:53 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[best practices]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[random thoughts]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1405</guid>
		<description><![CDATA[(not sure if the pirate image + caption was created by Zeh Fernando, he sent it to me a couple years ago, forgot to ask him&#8230;) Another polemic subject and something that I&#8217;ve been delaying for a while, I&#8217;ll try to explain how I got to my conclusions and I&#8217;m sure a lot of people [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://blog.millermedeiros.com/wp-content/uploads/2012/01/arrr_im_a_private.jpg" alt="arrr im a private, you cant access me" width="630" height="516" class="alignnone size-full wp-image-1414" /><br />
<small>(not sure if the pirate image + caption was created by <a href="http://zehfernando.com/">Zeh Fernando</a>, he sent it to me a couple years ago, forgot to ask him&#8230;)</small></p>
<p>Another polemic subject and something that I&#8217;ve been delaying for a while, I&#8217;ll try to explain how I got to my conclusions and I&#8217;m sure a lot of people won&#8217;t agree until they experience the same problem or realize how often it may happen on a real project and specially if it does happen with a code you don&#8217;t &#8220;own&#8221; and/or can&#8217;t change without compromising future updates&#8230; The advice is mostly about JavaScript <small>(since it&#8217;s what I&#8217;ve been coding more lately and where I think the issue is bigger)</small> but it also fits other languages.</p>
<p>Not so long ago I had an opposite opinion about this subject <small>- I would always set everything to private and only changed to protected/public if needed -</small> try to understand what made me change my opinion and pay attention every time you find yourself &#8220;tied&#8221; or doing lots of hacks just because you can&#8217;t monkey-patch a simple function/variable.</p>
<p><span id="more-1405"></span></p>
<h3>Private variables and functions in JavaScript</h3>
<p>Unlike Java/C#/AS3/PHP, JavaScript doesn&#8217;t have keywords for defining if a variable/function/object is private/public/protected/final/etc <small>(acessor keywords)</small>&#8230; But since it has closures and each closure has it&#8217;s own scope we can <a href="http://javascript.crockford.com/private.html">emulate some of these access controls</a>, a private variable is simply a variable declared inside an &#8220;unreachable scope&#8221;. Example:</p>
<pre class="brush:js">
// global variable
var lorem = 'ipsum';

(function(){
    // the immediately invoked function expression (IIFE) will create a closure
    // all vars and functions inside this scope will be "private"
    var foo = 'bar';

    console.log(lorem); // 'ipsum'
    console.log(foo);   // 'bar'
}());

console.log(lorem); // 'ipsum'
console.log(foo);   // undefined
</pre>
<p>Because of this powerful and useful language feature a lot of people been using design patterns like the <a href="http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript">revealing module pattern</a> to avoid polluting the global scope and to better organize their applications <small>(including myself)</small>.</p>
<p><strong>Private variables are usually a good thing since they avoid more problems than they cause</strong>, naming conflicts <small>(two pieces of code using same name to store different info)</small> can be very hard to track and it is very common to happen, that&#8217;s one of the main reasons why people use so many private variables, but like most things in life it also has it&#8217;s drawbacks and I&#8217;ll show a few cases where it can be an issue and how to <em>avoid</em> it.</p>
<h3>Other languages</h3>
<p>Java/C#/AS3/PHP have the concept of a <code>protected</code> class member, the <code>protected</code> member is like a <code>private</code> one but that can be overwritten by a <em>child</em> class.  By using <code>protected</code> on all your members instead of using <code>private</code> you increase the flexibility of your code, if the user wants to change the default behavior of a method he can simply extend the class and overwrite it. The sad part is that <code>private</code> variables in JS can&#8217;t be overwritten, not even by <em>child classes</em>.</p>
<h3>JavaScript is about monkey-patching</h3>
<p>I saw this quote on Twitter a few weeks ago and I must agree:</p>
<blockquote><p>
  Monkey patching in javascript is called &#8220;writing code.&#8221; &#8211; <a href="https://twitter.com/#!/rockstar_/status/147367323488108544">Paul Hummer</a>
</p></blockquote>
<p>One of the greatest things about the language and what makes it so fun to code is that you can get very <em>creative</em> about how to solve certain problems, it gives you freedom enough to do to terrible and amazing things at the same time, you don&#8217;t feel as constrained as on a static strong-typed language&#8230;</p>
<p>Private variables are against monkey-patching and can make your code impossible to be reused/tweaked without a lot of manual work, one of the main reasons for that is because the variable is inside a scope that you can&#8217;t reach, not even if you extend the object, it&#8217;s like if all your variables and methods where <code>private final</code> <small>(you can&#8217;t overwrite it by any means)</small>, and this process isn&#8217;t &#8220;scalable&#8221; at all.</p>
<h3>Unit Testing</h3>
<p>Another problem with private members is that it is harder to test them.  I usually tend to think that private members doesn&#8217;t need to be tested since the public interface is already being tested, but sometimes that may not be the truth <small>(think about a variable that holds state info or some property that needs to be swapped with a mock object)</small>. Exposing larger chunks of your codebase <small>(as a pseudo-private member)</small> may help you to increase your unit tests coverage and also to simplify the tests.</p>
<h3>Solution</h3>
<p><a href="http://blog.millermedeiros.com/wp-content/uploads/2012/01/expose_all_the_things.png"><img src="http://blog.millermedeiros.com/wp-content/uploads/2012/01/expose_all_the_things.png" alt="" title="expose all the things" width="630" height="414" class="alignnone size-full wp-image-1409" /></a></p>
<p>What I&#8217;ve been doing on some projects is to expose most of the methods and properties of objects that I know that are going to be reused in multiple projects <small>(like open-source projects)</small>, if it isn&#8217;t meant to be called by other people or is subject to changes I simply start the name with an underscore (<code>_</code>), it&#8217;s a sign that you shouldn&#8217;t expect the function to be there forever <small>(pseudo-private)</small> but it allows the user to easily &#8220;hack&#8221; the original code to make it work as he want. <strong>I believe that code that is easy to edit is way more valuable than code that has lots of settings to try to fit all scenarios</strong>, there will be a always an edge case that isn&#8217;t covered or the application will be so complex/bloated that nobody will want to use it.</p>
<p>I&#8217;m not saying you should pollute the global scope with thousands of variables <small>(ie. keep it as properties of an object, like if it was a namespace)</small>, but consider exposing things that you may want other people to be able to tweak/reuse, been doing it for a while and it saved me some headaches.</p>
<h3>A real case where monkey-patching &#8220;saved the day&#8221;</h3>
<p>I wanted to add JSON support to <a href="https://github.com/scrooloose/syntastic">Syntastic Vim</a> but JSONLint output contained multiple lines and making syntastic to understand the format was kinda tricky so I decided to do a <a href="https://github.com/zaach/jsonlint/pull/15">pull request on JSONLint</a> itself adding an option for toggling the error message format, if the method <code>parseError</code> wasn&#8217;t exposed on the <em>lexer</em> object the change could be way more complex. That&#8217;s the difference of taking 20min to release a new feature that affects 2 open-source projects <small>(and that boosted my productivity a lot since now I can validate JSON files at each save)</small> or taking 1 day or more or not even doing it&#8230;</p>
<h3>A real example where private members made things more complex than needed</h3>
<p>I wanted to generate HTML documentation for <a href="http://millermedeiros.github.com/amd-utils/">AMD-Utils</a> based on a few markdown files that I had on the repository, just because it would be quicker to browse it, so I decided to code <a href="https://github.com/millermedeiros/mdoc">a simple generator</a> that would read all the markdown files, process them and output to HTML. The only issue is that I got used to <a href="http://github.github.com/github-flavored-markdown/">Github flavored markdown syntax</a> and all my markdown files were written using this syntax, so I had to tweak the markdown parser a little bit to act like the way github renders the README files <small>(it is not the same as the JavaScript preview)</small> which means I had to do some pre-processing before <a href="https://github.com/isaacs/github-flavored-markdown">showdown</a> did &#8220;it&#8217;s magic&#8221; and also <strong>edit showdown source code to comment out a single line, yes, <a href="https://github.com/millermedeiros/mdoc/blob/264524a3/src/js/lib/showdown.js#L1167">a single line</a>!!</strong>  Because Github doesn&#8217;t hard-wrap line breaks on README files while the JS preview does it.</p>
<p>If showdown exposed all the methods I could override the <code>_FormParagraphs</code> method or do some <em>magic</em> before and after the original <code>_FormParagraphs()</code> was called <small>- basically convert all the line breaks into <em>tokens</em> before <code>_FormParagraphs()</code> and <em>untokenize</em> it afterwards -</small> and I could keep the library as a normal npm dependency <small>- so I could update it as long as they didn&#8217;t replaced the method functionality or renamed it -</small> things could still go wrong but the &#8220;damage&#8221; would be controlled. It would also reduce the chance of updating the file without noticing that it had changes that diverged from the original lib <small>(since the changes are on a separate file)</small>.</p>
<p>Another option would be to fork the project and add support for toggling the <abbr title="Github Flavored Markdown">GFM</abbr> settings, but that would take way more time than I wanted to spend and I would need to wait the change to be merged and pushed to npm <small>(if the pull request was even accepted)</small>.</p>
<h3>Conclusion</h3>
<p>I&#8217;ve seen the same thing happening over and over again on many projects <small>(in many different languages)</small> and that&#8217;s why I&#8217;ve been favoring the &#8220;expose ALL the things&#8221; approach lately.</p>
<p>Notice that I still create many local variables and functions since it&#8217;s less verbose and not all code should/need to be heavily <em>tweakable</em> <small>(I can edit the source code of my app as much as I want, no need to monkey-patch)</small> but if you expect a lot of people to reuse your code please make it easier for them to patch it. You should <em>warn</em> people of the <em>danger</em> but assume they know what they are doing, we are all grown ups right?</p>
<p><strong>Understand the reasoning behind a &#8220;best practice&#8221; so you can decide if it does apply to your case or not.</strong></p>
<p>That&#8217;s it!</p>
<h3>Further Reading</h3>
<ul>
<li><a href="http://steve-yegge.blogspot.com/2010/07/wikileaks-to-leak-5000-open-source-java.html">Wikileaks To Leak 5000 Open Source Java Projects With All That Private/Final Bullshit Removed </a> <small>(external)</small></li>
<li><a href="http://blog.millermedeiros.com/2010/09/there-is-no-spoon/">There is no spoon</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/a-case-against-private-variables-and-functions-in-javascript/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Node.js as a build script</title>
		<link>http://blog.millermedeiros.com/node-js-as-a-build-script/</link>
		<comments>http://blog.millermedeiros.com/node-js-as-a-build-script/#comments</comments>
		<pubDate>Tue, 03 Jan 2012 06:31:54 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1382</guid>
		<description><![CDATA[There are a lot of build tools that covers specific use cases and/or try to cover as many scenarios as possible, amongst the most famous ones are make, rake, Ant and maven. I&#8217;m going to talk about why I&#8217;ve been favoring plain Node.js scripts as my &#8220;build tool&#8221; and how to do some simple things. [...]]]></description>
			<content:encoded><![CDATA[<p>There are a lot of build tools that covers specific use cases and/or try to cover as many scenarios as possible, amongst the most famous ones are <a href="http://www.gnu.org/software/make/">make</a>, <a href="http://rake.rubyforge.org/">rake</a>, <a href="http://ant.apache.org/">Ant</a> and <a href="http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html">maven</a>.  I&#8217;m going to talk about why I&#8217;ve been favoring plain Node.js scripts as my &#8220;build tool&#8221; and how to do some simple things. This work flow may not be the <em>best</em> one for you and your team, understand the reasoning behind it and pick the tools based on your needs and preferences.</p>
<p><span id="more-1382"></span></p>
<h3>Why?</h3>
<p>Most of my projects I just need some basic features like file concatenation, running an optimizer/compressor, some simple string replacements or running some other 3rd party command-line tool, sometimes I also need to do some things that aren&#8217;t that common <small>(code generation, documentation, etc..)</small> and also depending on the project my structure may not fit existing tools.</p>
<p>I&#8217;ve been using Ant for the past few years on almost all my projects, the good thing about Ant is that it&#8217;s very mature, can run on multiple platforms, well documented, pre-installed on Mac OS X, popular <small>(specially for Java and AS3 developers)</small>, and almost anything you want to do you just need to search for the &#8220;term&#8221; plus &#8220;ant task&#8221; <small>(eg. &#8220;concat files ant task&#8221;, &#8220;delete files ant task&#8221;)</small> and the first results probably describe how to do what you need. The problem with Ant is that XML is a markup language and when you try to do things that requires a programming language <small>(logic, loops, etc..)</small> things get nasty really quickly so you need to extend Ant by using the <a href="http://ant.apache.org/manual/Tasks/script.html">script task</a> or creating an external command line tool/app or an <a href="http://ant.apache.org/manual/develop.html">Ant plugin</a> (Java), not really convenient or straightforward <small>(too much overhead, need to learn new APIs and/or languages&#8230;)</small></p>
<p>Make and bash scripts are way more concise than Ant, but they also impose a barrier to people that doesn&#8217;t know how to edit them. Another problem with bash is that it isn&#8217;t very portable which for me is a big issue, I work with multiple devs and who knows which OS they might be using or how the build process will be triggered? It&#8217;s very important for users to be able build the project without too much trouble and also that multiple developers on the team understands how the build process work and how to edit the files, it will avoid &#8220;knowledge silos&#8221; and &#8220;code ownership&#8221;. If your team is proficient in JavaScript I suggest that the build script should be written in JavaScript, if the team is more comfortable with Python or Ruby <small>(or anything else)</small> than write it on these languages instead&#8230;</p>
<p>A few months ago I finally decided to try &#8220;vanilla&#8221; Node.js scripts and I&#8217;m very pleased with it, I see it as an excuse to learn Node.js API and it&#8217;s libraries. It&#8217;s also very fast to code since I&#8217;m very familiar with JavaScript syntax, I don&#8217;t need to spend time searching how to do things I simply code it, also since I&#8217;m not constrained by an existing tool structure I can go &#8220;nuts&#8221; and code whatever I want and the way I want it, the complexity of my scripts are only limited by my needs and deadlines.</p>
<p>I tend to think that tools that try to fit all scenarios end up not fitting anything properly, so I prefer code that is easy to edit/tweak than code that can be overly customized. Having the build script written on the same language as the project is a very good thing since contributors will feel more comfortable at updating it and improving it, low entry barrier is usually a good motivation for contributing.</p>
<h3>How?</h3>
<p>I&#8217;m not really using any specific build tool, just putting together a few <a href="http://npmjs.org">npm</a> modules as needed, kinda following <a href="http://blog.nodejitsu.com/the-nodejs-philosophy">the Node.js philosophy</a> of keeping packages small and loosely coupled, some of the modules I&#8217;ve used so far and that helped a lot in the process:</p>
<ul>
<li><a href="https://github.com/visionmedia/commander.js/">commander</a>
<ul>
<li>very useful tool to generate self-documenting command-line interfaces,<br />
using it on most of my Node.js command-line tools.</li>
</ul>
</li>
<li><a href="https://github.com/ryanmcgrath/wrench-js">wrench-js</a>
<ul>
<li>recursive file operations (delete, create, copy directories)</li>
</ul>
</li>
<li><a href="https://github.com/isaacs/node-glob">node-glob</a>
<ul>
<li>returns a list of filepaths based on a string pattern.</li>
</ul>
</li>
<li><a href="http://www.handlebarsjs.com/">handlebars</a>
<ul>
<li>for templating in case you need to do some code generation and/or process<br />
some text files.</li>
</ul>
</li>
<li><a href="https://github.com/mishoo/UglifyJS">UglifyJS</a>
<ul>
<li>JavaScript minification.</li>
</ul>
</li>
<li><a href="https://github.com/caolan/async">async</a>
<ul>
<li>Asynchronous utilities and control flow.</li>
</ul>
</li>
</ul>
<p>I&#8217;m also calling external tools when needed using the <a href="http://Node.js.org/docs/latest/api/child_processes.html#child_process.exec">child_process.exec</a> command, so you can still call some JAR files or other command-line tools if needed&#8230;</p>
<p>I&#8217;m not using any build tool <strong>because I want flexibility</strong> and also because it&#8217;s very easy to put those things together, there are a plenty of Node.js modules available through npm that does all sorts of things and it&#8217;s a very good excuse to learn how to use them and to discover new libraries.</p>
<h3>Examples</h3>
<p>Most of the examples are very trivial, use it as a reference not as the only way of doing it.</p>
<h4>Concat files</h4>
<p>You just need to read the content of a file list and merge them:</p>
<pre class="brush:js">
// settings
var FILE_ENCODING = 'utf-8',
    EOL = '\n',
    DIST_FILE_PATH = 'dist/myAwesomeScript.js';

// setup
var _fs = require('fs');

function concat(fileList, distPath) {
    var out = fileList.map(function(filePath){
            return _fs.readFileSync(filePath, FILE_ENCODING);
        });
    _fs.writeFileSync(distPath, out.join(EOL), FILE_ENCODING);
    console.log(' '+ distPath +' built.');
}

concat([
    'foo/bar.js',
    'foo/lorem.js',
    'foo/maecennas.js'
], DIST_FILE_PATH);
</pre>
<p>It&#8217;s important to notice that I&#8217;m not concatenating files that much since I&#8217;m using <a href="https://github.com/jrburke/r.js/">r.js</a> <small>(RequireJS optimizer)</small> on almost all my projects, r.js can be also used to merge CSS files <small>(inline <code>@import</code>ed stylesheets)</small>.</p>
<h4>Minify JS file with UglifyJS</h4>
<pre class="brush:js">// settings
var FILE_ENCODING = 'utf-8';

function uglify(srcPath, distPath) {
    var
      uglyfyJS = require('uglify-js'),
      jsp = uglyfyJS.parser,
      pro = uglyfyJS.uglify,
      ast = jsp.parse( _fs.readFileSync(srcPath, FILE_ENCODING) );

    ast = pro.ast_mangle(ast);
    ast = pro.ast_squeeze(ast);

    _fs.writeFileSync(distPath, pro.gen_code(ast), FILE_ENCODING);
    console.log(' '+ distPath +' built.');
}

uglify('dist/awsum.js', 'dist/awsum.min.js');
</pre>
<h4>Minify JS with google closure compiler (run external JAR)</h4>
<p>You can run shell commands with <a href="http://Node.js.org/docs/latest/api/child_processes.html#child_process.exe">child_process.exec</a>.  Very useful for reusing existing command-line tools and code that isn&#8217;t Node.js specific.</p>
<pre class="brush:js">// --- SETTINGS ---
var COMPILER_JAR = 'build/compiler.jar';

// --- SETUP ---
var _exec = require('child_process').exec;

function compile(srcPath, distPath) {
    // exec is asynchronous
    _exec(
      'java -jar '+ COMPILER_JAR +' --js '+ srcPath +' --js_output_file '+ distPath,
      function (error, stdout, stderr) {
        if (error) {
          console.log(stderr);
        } else {
            console.log(' '+ distPath + ' built.');
        }
      }
    );
}

compile('dist/myAwesomeScript.js', 'dist/myAwesomeScript.min.js');
</pre>
<h4>Use commander to parse CLI arguments</h4>
<p><a href="https://github.com/visionmedia/commander.js/">Commander.js</a> is very useful for parsing command-line arguments, specially since it is self-documenting and extremely easy to use.</p>
<pre class="brush:js">// --- SETTINGS ---
var DIST_PATH = 'dist/awsum.js';

// --- SETUP ---
var _cli = require('commander'),
    _fs = require('fs');

// global options
_cli
    .version('0.0.1')
    .option('--silent', 'suppress log messages.');

// commands
_cli
    .command('deploy')
    .description('Optimize site for deploy.')
    .action(deploy);

_cli
    .command('purge')
    .description('Delete old files from dist folder.')
    .action(purgeDeploy);

// parse commands
_cli.parse(process.argv);

function deploy() {
    purgeDeploy();
    build();
}

function purgeDeploy(){
    _fs.unlinkSync(DIST_PATH);
    if (! _cli.silent) {
        console.log(' Deleted deploy files!');
    }
}

function build(){
    // concat files here or do anything that generates the dist files
    if (! _cli.silent) {
        console.log(' Built!');
    }
}
</pre>
<p><code>node build -h</code> will show the available commands and options. Running <code>node build deploy</code> will execute the &#8220;deploy&#8221; command, <code>node build deploy --silent</code> will execute the &#8220;deploy&#8221; command but suppress log messages.</p>
<h4>Code generation / String replacements</h4>
<p>Template engines aren&#8217;t useful only for HTML documents, they can be used for simple string replacements and also for code generation. I&#8217;ve been favoring <a href="http://handlebarsjs.com/">Handlebars.js</a> because of the &#8220;helpers&#8221; and nested paths support. I&#8217;ve been using it to add some basic info like version number, build date and even to generate some source files.</p>
<p>On <a href="http://millermedeiros.github.com/amd-utils">AMD-Utils</a> I&#8217;m using it to generate the package files and also to update the test runners <small>(so I make sure I have unit tests to all modules)</small>.</p>
<p>If you are distributing the library through npm and/or have a <code>packages.json</code> file it is a good idea to reuse the data on the build as well so it doesn&#8217;t get out of sync. Let&#8217;s say we have a license at the top of the file like:</p>
<pre class="brush:js">/**@license
 * My Awesome Lib &lt;http://example.com&gt;
 * Version: 0.1.0 (Tue, 03 Jan 2012 03:48:58 GMT)
 * License: MIT
 */
</pre>
<p>It could be described as:</p>
<pre class="brush:js">/**@license
 * {{name}} &lt;{{homepage}}&gt;
 * Version: {{version}} ({{build_date}})
 * License: {{#license licenses}}
 */
</pre>
<p>And we could replace the data using handlebars:</p>
<pre class="brush:js">var FILE_ENCODING = 'utf-8',
    DIST_PATH = 'dist/awsum.js';

var _handlebars = require('Handlebars'),
    _fs = require('fs');

// will generate a CSV if package.json contains multiple licenses
_handlebars.registerHelper('license', function(items){
    items = items.map(function(val){
        return val.type;
    });
    return items.join(', ');
});

var distContent = _fs.readFileSync(DIST_PATH, FILE_ENCODING);
var template = _handlebars.compile(distContent);

//reuse package.json data and add build date
var data = JSON.parse( _fs.readFileSync('package.json', FILE_ENCODING) );
data.build_date = (new Date()).toUTCString();

_fs.writeFileSync(DIST_PATH, template(data), FILE_ENCODING);
</pre>
<h4>Lint JS files and prompt user to confirm before continuing <small>added 2012/01/03</small></h4>
<p>Joss Crowcroft <a href="http://blog.millermedeiros.com/2012/01/node-js-as-a-build-script/#comment-11691">asked for it in the comments</a> and since it isn&#8217;t hard to implement <small>(thanks to Commander.js <code>.choose()</code> method)</small> I decided to do it.</p>
<pre class="brush:js">
var _cli = require('commander'),
    _jshint = require('jshint'),
    _fs = require('fs');

function lint(path, callback) {
    var buf = _fs.readFileSync(path, 'utf-8');
    // remove Byte Order Mark
    buf = buf.replace(/^\uFEFF/, '');

    _jshint.JSHINT(buf);

    var nErrors = _jshint.JSHINT.errors.length;

    if (nErrors) {
        console.log(' Found %j lint errors on %s, do you want to continue?', nErrors, path);
        _cli.choose(['no', 'yes'], function(i){
            if (i) {
                process.stdin.destroy();
                if(callback) callback();
            } else {
                process.exit(0);
            }
        });
    } else if (callback) {
        callback();
    }
}

// run
lint('dist/awsum.js', function(){
    console.log(' Built!');
});
</pre>
<h3>More</h3>
<p>There are a few Node.js general purpose build tools like <a href="https://github.com/mde/jake">node-jake</a> and <a href="http://jashkenas.github.com/coffee-script/documentation/docs/cake.html">cake</a> <small>(coffeescript)</small>, and also some tools that assumes your project is following a specific structure and contains options for lint/concatenation/minification like <a href="https://github.com/fat/smoosh">smoosh</a>, <a href="https://github.com/balupton/buildr.npm">buildr.npm</a> and <a href="https://github.com/cowboy/grunt">grunt</a>. I tend to prefer tools that doesn&#8217;t impose a specific structure since we never know if the constraints might become an issue or when the project requirements may change, but these tools may be a good option depending on the project.</p>
<p>If you need to do something that isn&#8217;t listed here <a href="http://search.npmjs.org/">search npm</a>, there is a big chance that someone already coded a package that does what you need, if not, do it yourself and share with the open source community.</p>
<p>I&#8217;ve also created a <a href="https://gist.github.com/2640928">gist with a RequireJS optimization example + copying/filtering files</a>, not as easy to follow as the previous examples but might be helpful to someone trying to make something a little bit more complex.  </p>
<p>That&#8217;s it for now.</p>
<p><ins datetime="2012-01-03T14:57:29+00:00"><strong>Edit 2012/01/03:</strong> Added JSHint example with confirm prompt and link to caolan/async.</ins><br />
<ins datetime="2012-05-09T00:50:53+00:00"><strong>Edit 2012/05.08:</strong> Added link to <a href="https://gist.github.com/2640928">gist</a> containing a full build script.</ins></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/node-js-as-a-build-script/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>FTP protip: move files instead of deleting</title>
		<link>http://blog.millermedeiros.com/ftp-protip-move-files-instead-of-deleting/</link>
		<comments>http://blog.millermedeiros.com/ftp-protip-move-files-instead-of-deleting/#comments</comments>
		<pubDate>Tue, 27 Dec 2011 19:23:35 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[protip]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1367</guid>
		<description><![CDATA[Lately I&#8217;ve been favoring SSH to upload/delete files from a server since it&#8217;s faster and I feel it gives me more control/power, but I still use a regular FTP client for most of my daily use (since I don&#8217;t have SSH access to all servers), this is just a very basic tip that some people [...]]]></description>
			<content:encoded><![CDATA[<p>Lately I&#8217;ve been favoring SSH to upload/delete files from a server since it&#8217;s faster and I feel it gives me more control/power, but I still use a <a href="http://filezilla-project.org/">regular FTP client</a> for most of my daily use <small>(since I don&#8217;t have SSH access to all servers)</small>, this is just a very basic tip that some people may not be aware of and that can boost productivity and reduce downtime during updates.</p>
<h3>The Workflow</h2>
<ol>
<li>Upload new files to a <code>_swap</code> directory.</li>
<li>Move current files to a <code>_backup</code> directory.</li>
<li>Move new files from <code>_swap</code> to the parent directory.</li>
<li>Test live files.</li>
<li>Delete files inside the <code>_backup</code> directory.</li>
<li>Win one free internet.</li>
</ol>
<h3>Why?</h2>
<p>The main reason is because <strong>moving files on FTP is way faster than deleting</strong> them, <strong>specially if you are moving the files to a parent directory</strong>, it can reduce the downtime from a couple minutes to a few seconds depending on how many files you are updating.</p>
<p>Another reason is that you will have a backup of the current files on the server and you can easily revert the changes in case anything goes wrong. <small>- You should also keep all source files on a version control system and make updates when the site has as few users as possible (usually from 9pm to 9am) to reduce the chance of ruining everything&#8230;</small></p>
<p>That&#8217;s it!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/ftp-protip-move-files-instead-of-deleting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>mdoc: markdown documentation generator</title>
		<link>http://blog.millermedeiros.com/mdoc-markdown-documentation-generator/</link>
		<comments>http://blog.millermedeiros.com/mdoc-markdown-documentation-generator/#comments</comments>
		<pubDate>Mon, 28 Nov 2011 03:24:16 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[documentation]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[opensource]]></category>
		<category><![CDATA[parser]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1354</guid>
		<description><![CDATA[Lately I&#8217;ve been avoiding inline documentation specially because JavaScript is a very loose language and I feel that inline-docs add too much noise to the code&#8230; But since documentation is very important if you want other people to use your code or if you have a large codebase I decided to create a simple documentation [...]]]></description>
			<content:encoded><![CDATA[<p>Lately I&#8217;ve <a href="http://blog.millermedeiros.com/2011/03/inline-documentation-why-im-ditching-it/">been avoiding inline documentation</a> specially because JavaScript is a very loose language and I feel that inline-docs add too much noise to the code&#8230; But since documentation is very important if you want other people to use your code or if you have a large codebase I decided to create a simple documentation generator using nodejs to parse external markdown files. I tried to find other tools but none of them had all the features I wanted so I decided to code mine.</p>
<p>So far it&#8217;s <em>a little rough around the edges</em>, code can be cleaned a lot <small>(I coded it really fast)</small> and it isn&#8217;t as flexible/polished as I want it to be, but it&#8217;s working fine for my current needs.</p>
<p>The <a href="https://github.com/millermedeiros/mdoc">project is on Github</a> and repository contains some example files with comments, you can check the <a href="http://millermedeiros.github.com/amd-utils">amd-utils documentation</a> for a live example <small>- amd-utils documentation uses a custom template but it&#8217;s very close to mdoc default template, only extra feature is the &#8220;specs&#8221; and &#8220;source&#8221; links (since other projects probably have a different file/folder structure).</small></p>
<p>I&#8217;m not sure when I will have time to improve it but I already added a couple feature requests to the issue tracker. <a href="https://github.com/millermedeiros/mdoc">Watch it, fork it and contribute!</a> If you want to report bugs and feature requests please use the <a href="https://github.com/millermedeiros/mdoc/issues">Github issue tracker</a>.</p>
<p>That&#8217;s it!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/mdoc-markdown-documentation-generator/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Generating &#8220;non-biased&#8221; random integers</title>
		<link>http://blog.millermedeiros.com/generating-non-biased-random-integers/</link>
		<comments>http://blog.millermedeiros.com/generating-non-biased-random-integers/#comments</comments>
		<pubDate>Wed, 16 Nov 2011 16:57:10 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1325</guid>
		<description><![CDATA[If you know Number Theory or had algorithms classes in college you can probably skip this post&#8230; - I studied Graphic Design so I had to learn those things by myself - I will try to explain it using as less math as possible.. I know there is a lot of info about this subject [...]]]></description>
			<content:encoded><![CDATA[<p><strong>If you know Number Theory or had algorithms classes in college you can probably skip this post&#8230;</strong> <small>- I studied Graphic Design so I had to learn those things by myself -</small> I will try to explain it using as less math as possible.. I know there is a lot of info about this subject on the internet and algorithms books but today I spent a couple minutes searching for it and most of them are too hard to understand if you are not a mathematician <small>(which BTW I&#8217;m not..)</small> so after giving up on the hard reading I decided to come up with my own solution to the problem, it may not be most elegant solution but it is at least a logical solution and results are <em>acceptable</em>.</p>
<p><span id="more-1325"></span></p>
<h3>Doing it wrong</h3>
<p>I already had a simple function to generate random floating point numbers inside a range, a simplified version of it looks like:</p>
<pre class="brush:js">
function rand(min, max) {
    return lerp(Math.random(), min, max);
}

function lerp(ratio, start, end) {
    return start + (end - start) * ratio;
}
</pre>
<p>The logic is pretty straightforward, <code>Math.random()</code> returns a random number from <code>0</code> to <code>1</code>, the <code>lerp()</code> method calculates the &#8220;linear interpolation&#8221; between <code>start</code> and <code>end</code>, here is an example:</p>
<pre class="brush:js">
lerp(0.5, 0, 100);  // 50
lerp(0.2, 0, 10);   // 2
lerp(0.5, -10, 10); // 0
</pre>
<p>Since &#8220;lerp ratio&#8221; is also a value inside the range <code>0...1</code> it is just a matter of doing the linear interpolation to a random ratio, nothing wrong about this process&#8230; One may think that since the random float works properly it would be just fine to use <code>Math.round()</code> to get a random integer:</p>
<pre class="brush:js">
//biased! don't use this code!
function randInt(min, max) {
    return Math.round( rand(min, max) );
}
</pre>
<p>Consider this example:</p>
<pre class="brush:js">
randInt(-1, 1);
</pre>
<p>What is the probability of getting <code>0</code>, <code>1</code> and <code>-1</code> respectively? If you think it&#8217;s ~33% than you are wrong, <code>0</code> has 50% of probability since anything inside the range <code>-0.5...0.5</code> is going to rounded to <code>0</code> <small>- I already knew it before I coded the naive approach but at that time I didn&#8217;t needed any sort of precision -</small> <strong>It is important to note that the problem only affects the min/max values no matter how large is the range.</strong></p>
<p>Running this code 1000x:</p>
<pre class="brush:js">
// first run
-1 =&gt; 24.7%
 0 =&gt; 50.2%
 1 =&gt; 25.1%

// second run
-1 =&gt; 24.8%
 0 =&gt; 51.6%
 1 =&gt; 23.5%
</pre>
<p>Y U NO LIKE -1 and 1?</p>
<h3>So how to do it &#8220;right&#8221;?</h3>
<p>First thing I did was to think how I would approach the problem on the simplest way possible that wouldn&#8217;t require reading a technical paper about <abbr title="Random Number Generators">RNG</abbr> which includes way more info than most people probably need to know&#8230;</p>
<p>Another option was reading Python source code <small>(as suggested by <a href="http://twitter.com/#!/gabriel_laet/statuses/136633034475712513">Gabriel Laet on twitter</a>)</small> but my gut said the implementation was more complex than I needed so I decided to try to solve the problem myself without any external help <small>(I like puzzles and this one didn&#8217;t looked that hard since we already have <code>Math.random()</code> in JavaScript).</small></p>
<p>For me the most important thing at solving this kind of problems is breaking it into smaller ones. The real issue with the previous approach is that the &#8220;range&#8221; that &#8220;covered&#8221; a single result <small>(zero)</small> was 50% of the full range, to solve the problem we need to break the range into 3 equal-sized steps <small>(since the range has 3 integers)</small> and pick a random &#8220;step&#8221;/&#8221;index&#8221; instead of simply rounding the linear interpolation.</p>
<blockquote><p><em>&#8220;A problem well stated is a problem half solved&#8221;</em> &#8211; Charles F. Kettering</p></blockquote>
<h3>Solution(s)</h3>
<pre class="brush:js">
function randInt(min, max) {
    var stepSize = 1 / (max - min + 1),
        nSteps = Math.floor(Math.random() / stepSize);
    return min + nSteps;
}
</pre>
<p>The &#8220;step size&#8221; is calculated by dividing one by the amount of integers inside the range, so if range have 3 items it will be <code>1/3 === 0.3333333333333333</code> if range has 4 items it will be <code>1/4 === 0.25</code> and so on&#8230; <small>(exactly what we need)</small></p>
<p>By knowing the size of the &#8220;step&#8221;, and since it is always inside the range <code>0 &lt;= n &lt;= 1</code>, we can pick a random step by using <code>Math.random()</code>.</p>
<p>If <code>Math.random()</code> is inside the range <code>0...0.3333333333333332</code> it should return <code>0</code> <small>(zero steps)</small>, if it&#8217;s inside the range <code>0.3333333333333333...0.6666666666666665</code> it should return <code>1</code> <small>(one step)</small> and from <code>0.6666666666666666</code> to <code>1</code> it should return <code>2</code> <small>(two steps)</small>. That is a very common math operation so I abstract it as a separate method to make clearer what the code is doing, I call this method <code>countSteps()</code> since most times I needed this function was to &#8220;count the number of full steps&#8221; and I haven&#8217;t seen it on any other library to follow the same convention <small>(naming things is hard)</small>:</p>
<pre class="brush:js">
function countSteps(val, stepSize) {
    return Math.floor(val / stepSize);
}
</pre>
<p>So the code could be rewritten for better readability:</p>
<pre class="brush:js">
function randInt(min, max) {
    var stepSize = 1 / (max - min + 1);
    return min + countSteps(Math.random(), stepSize);
}
</pre>
<p>Running this code 1000x:</p>
<pre class="brush:js">
// first run
-1 =&gt; 31.1%
 0 =&gt; 34.7%
 1 =&gt; 34.1%

// second run
-1 =&gt; 36.1%
 0 =&gt; 33.4%
 1 =&gt; 30.4%
</pre>
<p>Not biased at all!</p>
<h4>Solution #2 <small>(added 2011/11/16)</small></h4>
<p>After the post I got a <a href="https://github.com/millermedeiros/amd-utils/pull/8">pull request</a> with another implementation that after a few tweaks got into this code:</p>
<pre class="brush:js">
function randInt(min, max) {
  var diff = max - min,
      rnd = Math.random();
  return rnd !== 1? Math.floor((diff + 1) * rnd) + min : min + diff;
}
</pre>
<p>The other solution came so fast that I didn&#8217;t even explored other options, I already had the method <code>countSteps()</code>.. and you know, </p>
<blockquote><p><em>&#8220;if you only have a hammer you tend to see every problem as a nail&#8221;</em> &#8211; Abraham Maslow</p></blockquote>
<p>This method does work properly because <code>(1 -(-1) + 1) === 3</code> and <code>Math.floor(Math.random() * 3)</code> will return <code>0, 1 or 2</code> unless <code>Math.random() === 1</code> which would return <code>3</code> making the method return a value greater than <code>max</code>.</p>
<h4>Solution #3 <small>(added 2011/11/16)</small></h4>
<p>While I was updating the post with more info to explain the problem only happens with the max/min values I realized it could be fixed with a simpler solution while still using the regular random method but <a href="http://blog.millermedeiros.com/2011/11/generating-non-biased-random-integers/#comment-9247">Fabio Caccamo </a> was quicker to post it <img src='http://blog.millermedeiros.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<pre class="brush:js">
function randInt(min, max) {
   // can't be `max + 0.5` otherwise it will round up if `rand`
   // returns `max` causing it to overflow range.
   return Math.round( rand(min - 0.5, max + 0.499999999999) );
}
</pre>
<p>It does work because the rounding issue only affect the <code>min</code> and <code>max</code> values and we are increasing the range so all the numbers have an equal chance&#8230; now I feel dumb for over-engineering a &#8220;simple&#8221; problem <img src='http://blog.millermedeiros.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<h3>Sum up</h3>
<p>I still find the first solution to be more readable, probably because I&#8217;m very used with the <code>countSteps</code> method and it uses more vars/methods that ends up describing what the method does&#8230; <small>(or maybe just because it is closer to the way my head works)</small> But there are indeed many ways to skin a cat&#8230;</p>
<p>I hope it got clearer how to think about this kind of problem and possible solutions <small>(and how to spot the problems as well).</small> My mind is very visual so I usually draw this kind of stuff to help thinking about solutions <small>- it took me way less time to find the solution after I drawn it on paper than I would spend searching the web or trying to decipher somebody else code -</small> try to find a way that works for you, explaining the problem to another person also helps a lot since it makes you think about what exactly you are trying to solve.</p>
<blockquote><p>It&#8217;s way easier to code when you know what is the real problem you are trying to solve.</p></blockquote>
<p>This problem was simple and I wrote it quickly <small>(solution and post)</small> but I hope you get the idea&#8230; Maybe it&#8217;s useful on a future project. I&#8217;m still trying to find a good name for a &#8220;curried&#8221; version of <code>randInt(-1, 1)</code> <small>(-1, 0, 1)</small> I already have two methods called <code>randBit()</code> <small>(0 or 1)</small> and <code>randSign()</code> <small>(-1 or 1)</small> since these ranges are so common I think they deserves their own method, the implementation is also simpler so it has better performance <small> &#8211; not that it should make a huge impact is most cases, for me it&#8217;s more a readability thing and not needing to pass parameters&#8230;</small></p>
<p>For more helper functions check the <a href="http://millermedeiros.github.com/amd-utils/">amd-utils on github</a>, I&#8217;ve been improving it based on my needs and adding new stuff that may be useful when I have the opportunity or when I realize some common pattern, extract it and find a name to describe it&#8230;</p>
<p><small>PS: I hate when people use complex terms to describe simple things, that&#8217;s why I tried to explain it on the simplest way possible, by using Math terms the Mathematicians hide the knowledge from people of other domains, nowadays I can understand some of the documents but a few years ago it was like trying to read Greek&#8230;</small></p>
<p>That&#8217;s it!</p>
<p><ins datetime="2011-11-16T17:43:27+00:00"><strong>Update (2011/11/2011):</strong> Added info about rounding issue only affecting min/max and added solutions #2 and #3.</ins></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/generating-non-biased-random-integers/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>js-signals v0.7.0 and CompoundSignal</title>
		<link>http://blog.millermedeiros.com/js-signals-v0-7-0-and-compound-signal/</link>
		<comments>http://blog.millermedeiros.com/js-signals-v0-7-0-and-compound-signal/#comments</comments>
		<pubDate>Fri, 11 Nov 2011 04:34:09 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[opensource]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1311</guid>
		<description><![CDATA[Last week I released a new version of js-signals, I usually avoid creating posts at each release since I think people can simply watch the project on Github or are already following me on twitter (and I always send a twit after each release) but I added a few &#8220;advanced&#8221; features that may be useful [...]]]></description>
			<content:encoded><![CDATA[<p>Last week I released a new version of <a href="http://millermedeiros.github.com/js-signals/">js-signals</a>, I usually avoid creating posts at each release since I think people can simply watch the project on Github or are already <a href="http://twitter.com/millermedeiros">following me on twitter</a> <small>(and I always send a twit after each release)</small> but I added a few &#8220;advanced&#8221; features that may be useful on specific cases, that&#8217;s why I decided to create a post about it, I think some explanation may help people identify good use cases for those features.</p>
<p><span id="more-1311"></span></p>
<h3>SignalBinding.params <small>(a.k.a non-semantical versioning at v0.6.3)</small></h3>
<p>v0.6.3 was supposed to be v0.7.0 and v0.7.0 was supposed to be v0.8.0, my bad&#8230; I changed the API a little bit from v0.6.2 to v0.6.3 and still released it as a &#8220;patch version&#8221; <small>(see <a href="http://semver.org/">semantic versioning</a> for more info).</small> So I&#8217;m going to also talk about one simple feature I added on v0.6.3 <small>(it was an one line change and I was already using it, that&#8217;s why I released as 0.6.3).</small></p>
<p>When adding a new listener to a signal you have the option to set an Array that will be passed to the listener during execution. e.g.:</p>
<pre class="brush:js; gutter:false;">
var loaded = new signals.Signal();

var loadedBinding = loaded.add(console.log, console);
//set the default parameters of binding
loadedBinding.params = ['lorem', 'ipsum'];

//will log "lorem ipsum dolor"
loaded.dispatch('dolor');
</pre>
<p>This can be very useful when you are adding listeners dynamically and want to pass some info to the listener, since js-signals already uses <code>apply</code> to set the execution context <small>(<code>this</code> object inside handler)</small> the implementation was very simple <small>(updated 1 line of code)</small> and it increased the flexibility a lot. Of course this feature shouldn&#8217;t be abused since you need to know the structure of the event handler and which parameters it does expect, but it is a nice and concise way to pass parameters and it can avoid creating a new function just for that need <small>(on a previous project I had to wrap some functions just for that use case).</small></p>
<h3>Signal.memorize / Signal.forget()</h3>
<p>This is a feature that I&#8217;ve been pondering for a long time, it&#8217;s a way to listen to events that &#8220;happened in the past&#8221;, yep it sounds strange but that is what it does, it allows you to add a listener after the event was already dispatched and it will trigger the event handler automatically passing the previously dispatched arguments.</p>
<pre class="brush:js; gutter:false;">
var started = new signals.Signal();

started.memorize = true; // default is false
started.dispatch('foo');

// add()/addOnce() will automatically fire listener if signal was dispatched before
// will log "foo" since it keep record of previously dispatched values
started.addOnce(console.log, console);

started.forget(); // forget previously dispatched values (reset signal state)
started.addOnce(console.log, console); // won't log till next dispatch (since it "forgot")
started.dispatch('bar'); // log "bar"
</pre>
<p>It can be useful for events like <code>initialized</code>, <code>started</code>, <code>loaded</code>, etc&#8230; It works similarly to a &#8220;promise&#8221; that was already &#8220;resolved&#8221;.</p>
<p>Initially I thought about implementing it as a new type of Signal, maybe called <code>AsyncSignal</code> or something like that, but at the end I decided to simply add the new property and method since implementation was way simpler/smaller and the usage as well, <strong>this is JavaScript not Java!!</strong></p>
<h3>Signal.has(listener)</h3>
<p>Never really needed this feature on any project but since it was already being used internally and was just one line I think it is worth making it public. Maybe it can be useful to someone.</p>
<pre class="brush:js; gutter:false;">
function onStart(a){
  console.log(a);
}
started.add(onStart);
started.has(onStart); // true
</pre>
<h3>Universal Module Wrapper (UMD)</h3>
<p>Until v0.6.3 js-signals was being distributed with separate files to each environment (nodejs, browser, AMD), since v0.7.0 you can use the same distribution file on all the environments and with almost no overhead, the boilerplate code is minimal and won&#8217;t affect performance.</p>
<h3>CompoundSignal / listening to multiple Signals at once</h3>
<p>I also spent a long time thinking about this feature, specially trying to decide if it should be merged into signals &#8220;core&#8221; or if it should be a separate project, at the end I decided to split it into it&#8217;s own repository since it isn&#8217;t that common to need this feature and it would make it easier to install it using <a href="http://npmjs.org/">npm</a>. I coded an ad-hoc solution to do the same thing before on a project but once I realized I needed the exact same thing on another project I thought it was better to abstract it and create a new type of Signal that could handle it transparently and that would be more flexible as well.</p>
<p>The <code>CompoundSignal</code> works like a group of signals which will be dispatched automatically after all the signals contained by the group are dispatched. Arguments are passed to listeners as Arrays on the same order as the signals were passed to the constructor.</p>
<pre class="brush:js; gutter:false;">
var endedAnimation = new signals.Signal();
var completedSomething = new signals.Signal();

// CompoundSignal is just a regular Signal that gets dispatched after the other
// signals are dispatched (and have a similar API)
var completedManyThings = new signals.CompoundSignal(endedAnimation, completedSomething);
completedManyThings.addOnce( doSomethingOnCompletedManyThings );

function doSomethingOnCompletedManyThings(paramsArr1, paramsArr2){
  //handler will receive parameters of each signal as arrays since
  //they can dispatch an arbitrary number of parameters
  console.log( paramsArr1, paramsArr2 );
}

completedSomething.dispatch('lorem', 'ipsum');

setTimeout(function(){
    endedAnimation.dispatch('ended animation');
}, 500);

//will log after 500ms: ['ended animation'], ['lorem', 'ipsum']
//note that params are on the same order as the signals were passed to
//CompoundSignal constructor not at the order they were dispatched
</pre>
<p>CompoundSignal is very powerful and flexible, although the implementation is actually very simple, check the <a href="https://github.com/millermedeiros/CompoundSignal">project repository</a> for more info and check the unit tests and source code for more details, it has some advanced features as well like overwriting previously dispatched values, dispatching same signal multiple times, resetting state, etc&#8230;</p>
<p>Nice thing to note is that <a href="https://github.com/millermedeiros/CompoundSignal/blob/593bc6c70d/src/CompoundSignal.js#L27-30"><code>CompoundSignal</code> uses <code>SignalBinding.params</code></a> to simplify the logic. That&#8217;s exactly the kind of stuff that motivated me to add the <code>SignalBinding.params</code>, so simple and useful&#8230;</p>
<h3>More</h3>
<p>I hope the new additions and explanations help you to code better asynchronous applications and to decouple your objects. Signals improved the quality of my code a lot and also reduced the amount of typo errors and scope issues <small>(the second parameter of <code>add</code> and <code>addOnce</code> can be used to set the value of the <code>this</code> object inside the listener)</small>, I hope it does the same for you.</p>
<p>Check more <a href="https://github.com/millermedeiros/js-signals/wiki/Examples">examples on the wiki</a> and watch <a href="http://millermedeiros.github.com/js-signals/">js-signals</a> and <a href="https://github.com/millermedeiros/CompoundSignal">CompoundSignal</a> on github. For feature requests, suggestions and bug reports please use the github issue tracker. There is also an <a href="http://millermedeiros.github.com/js-signals/docs/">online documentation</a> in case you need it&#8230;</p>
<blockquote><p>Asynchronous programming is hard, use tools that make the process easier and that also provides enough flexibility.</p></blockquote>
<p>That&#8217;s it for now.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/js-signals-v0-7-0-and-compound-signal/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The problem with CSS pre-processors</title>
		<link>http://blog.millermedeiros.com/the-problem-with-css-pre-processors/</link>
		<comments>http://blog.millermedeiros.com/the-problem-with-css-pre-processors/#comments</comments>
		<pubDate>Wed, 09 Nov 2011 05:16:14 +0000</pubDate>
		<dc:creator>Miller Medeiros</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[best practices]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[random thoughts]]></category>

		<guid isPermaLink="false">http://blog.millermedeiros.com/?p=1271</guid>
		<description><![CDATA[This post is very polemic, I thought a lot before publishing it, please try to be open-minded and read the whole thing before commenting, it is not supposed to become a flame war. Please read the about page to understand the objective of this blog and the way I think about it. I&#8217;ve been considering [...]]]></description>
			<content:encoded><![CDATA[<p><strong>This post is very polemic, I thought a lot before publishing it, please try to be open-minded and read the whole thing before commenting, it is not supposed to become a flame war.</strong> Please read the <a href="http://blog.millermedeiros.com/about/">about page</a> to understand the objective of this blog and the way I think about it.</p>
<p>I&#8217;ve been considering to use a CSS pre-processor like <a href="http://sass-lang.com/">SASS</a>, <a href="http://lesscss.org">LESS</a>, <a href="http://learnboost.github.com/stylus/">Stylus</a>, etc, for a very long time. Every time someone asked me if I was using any of these tools/languages I would say that I&#8217;m kinda used to my current workflow and I don&#8217;t really see a reason for changing it since the problems those languages solves are not really the problems I&#8217;m having with CSS. Then yesterday I read <a href="http://www.stuffandnonsense.co.uk/blog/about/less">two</a> blog <a href="http://www.anotheruiguy.com/2011/10/from-sass-to-less-and-right-back-with-sass/">posts</a> which made me reconsider my point of view so I decided to spend some time today studying the alternatives <small>(once again)</small> and porting some code to check the output and if the languages would really help to keep my code more organized/maintainable and/or if it would make the development process easier <small>(also if they evolved on the past few years).</small> </p>
<p><span id="more-1271"></span></p>
<p>It takes a couple hours for an experienced developer to learn most of the features present on these languages <small>(after you learn the first couple languages the next ones are way easier)</small> but if you have no programming skills besides CSS/HTML and/or don&#8217;t know basic programming logic <small>(loops, functions, scope)</small> it will probably take a while, the command line is another barrier to CSS/HTML devs&#8230; But that isn&#8217;t the focus of this post, I&#8217;m going to talk specifically about overused/misused features. I will try to explain the most common problems I see every time someone shows a code sample or I see a project written using any of these languages/pre-processors.</p>
<h3>Mixins</h3>
<h4>What are mixins?</h4>
<p>Mixin is a common name used to describe that an <em>object</em> should copy all the properties from another <em>object</em>. To sum up a mixin is nothing more than an advanced copy and paste. &#8220;All&#8221; the famous pre-processors have some kind of mixin.</p>
<h4>Dumb code duplication is dumb</h4>
<p>Following the SCSS syntax (sass), a mixin can be described and used as:</p>
<pre class="brush:css; gutter:false;">
@mixin error {
    color: #f00;
    border: 2px solid #fc0;
}

.error-default {
    @include error;
}

.error-special {
    @include error;
    background-color: #fcc;
}
</pre>
<p>Which will compile to:</p>
<pre class="brush:css; gutter:false;">
.error-default {
    color: #f00;
    border: 2px solid #fc0;
}

.error-special {
    color: #f00;
    border: 2px solid #fc0;
    background-color: #fcc;
}
</pre>
<p>Note that the properties are duplicated, which is very bad, file size will increase a lot and overall performance will also be degraded if not used with care. &#8211; Imagine that on a large project with thousands of lines of code, the amount of duplicated code will be <em>unacceptable</em> <small>(by my standards)</small>.</p>
<p>This problem isn&#8217;t specific to SASS, it is also present on LESS and Stylus and any other language/pre-processor which supports the same feature, by having a new layer of abstraction the developer won&#8217;t realize he is creating code that has lots of duplication&#8230;</p>
<h3>Extend</h3>
<p>LESS and Stylus doesn&#8217;t have support for anything similar to an extend, that&#8217;s why I picked SCSS (Sass) to write the code samples. A extend is like a &#8220;smarter mixin&#8221;, instead of copying and pasting the properties it will set the properties to multiple selectors at once.</p>
<pre class="brush:css; gutter:false;">
.error {
    color: #f00;
    border: 2px solid #fc0;
}

.error-default {
    @extend error;
}

.error-special {
    @extend error;
    background-color: #fcc;
}
</pre>
<p>Which will compile to:</p>
<pre class="brush:css; gutter:false;">
.error, .error-default, .error-special {
    color: #f00;
    border: 2px solid #fc0;
}

.error-special {
    background-color: #fcc;
}
</pre>
<p>Way closer to what a normal person would do manually&#8230; &#8220;Only&#8221; use mixins if you need to pass custom parameters. If you see yourself using the same mixin multiple times passing the same values than you should create a base &#8220;type&#8221; that is inherited by other selectors. <small>- <a href="http://compass-style.org">Compass</a> <small>(nice SASS framework)</small> have a lot of mixins which I think should be <em>base classes</em> instead.</small></p>
<h4>Extend isn&#8217;t enough</h4>
<p>Note that extend avoids code duplication but it also causes other problems, the amount of selectors can become an issue, if you <code>@extend</code> the same base class multiple times you may end up with a rule that have thousands of selectors, which won&#8217;t be good for performance either and can even make the <a href="https://github.com/nex3/sass/issues/12">browser to crash</a>.</p>
<p>Another issue is that every class you create to be used only by <code>@extend</code> is going to be included on the compiled file <small>(even if not used)</small> which can be an issue in some cases <small>(name collisions, file size)</small> and makes this process not viable for creating a framework like <a href="http://compass-style.org">compass</a>.</p>
<p>I really wish that SASS improves the way that <code>@extend</code> works <small>(and that the other pre-processors also implements a similar feature)</small> so we could create many base classes for code reuse but don&#8217;t necessarily export them. Something like:</p>
<pre class="brush:css; gutter:false;">
@abstract error {
    color: #f00;
    border: 2px solid #fc0;
}

.error-default {
    @extend error;
}

.error-special {
    @extend error;
    background-color: #fcc;
}
</pre>
<p>Which would compile to:</p>
<pre class="brush:css; gutter:false;">
.error-default, .error-special {
    color: #f00;
    border: 2px solid #fc0;
}

.error-special {
    background-color: #fcc;
}
</pre>
<p><small>PS: I know this kind of feature was <a href="http://groups.google.com/group/compass-users/msg/93e7a8cb250e5314">already</a> proposed <a href="https://github.com/nex3/sass/issues/102">before</a>.</small></p>
<h3>Extend and mixins can be bad for maintenance</h3>
<p>Contrary to the common knowledge, extending other classes and creating mixins can degrade maintenance. Since the place where you are using the properties is <em>far away</em> from where the properties are being defined there is a bigger chance that you will change properties without noticing you are affecting multiple objects at once, or not realizing which elements are being affected by the changes. This is called <strong>&#8220;tight coupling&#8221;</strong>:</p>
<blockquote>
<p>Tightly coupled systems tend to exhibit the following developmental characteristics, which are often seen as disadvantages:</p>
<ul>
<li>A change in one module usually forces a ripple effect of changes in other modules.</li>
<li>Assembly of modules might require more effort and/or time due to the increased inter-module dependency.</li>
<li>A particular module might be harder to reuse and/or test because dependent modules must be included.</li>
</ul>
<p><small>(source: <a href="http://en.wikipedia.org/wiki/Coupling_%28computer_programming%29">Wikipedia</a>)</small>
</p></blockquote>
<p><small>I prefer to group all my selectors by proximity, that way I make sure that when someone update a selector/property they know exactly what is going to be affected by these changes, even if that imply some code duplication.</small></p>
<h3>Nesting</h3>
<p>Another feature that a lot of people consider useful is selector nesting, so instead of repeating the selectors many times you simply nest the rules that should be applied to child elements.</p>
<pre class="brush:css; gutter:false;">
#content {

    table.hl {
        margin: 2em 0;

        td.ln {
            text-align: right;
        }

    }

}
</pre>
<p>Compiles to:</p>
<pre class="brush:css; gutter:false;">
#content table.hl {
    margin: 2em 0;
}

#content table.hl td.ln {
    text-align: right;
}
</pre>
<p>By abstracting the selectors it becomes very easy to be over specific and specificity is hard to handle and a bad thing for maintainability. I&#8217;ve been following the <a href="https://github.com/stubbornella/oocss/wiki/faq">OOCSS</a> approach and I don&#8217;t need child selectors that much so I don&#8217;t think that typing the same selector multiple times is a real problem <small>(specially with good code completion)</small>, I know a lot of people don&#8217;t agree with that approach but for the kind of stuff I&#8217;m doing it&#8217;s been working pretty well.</p>
<p>Call me a weirdo but I also find nested code harder to read <small>- since I&#8217;ve been coding non-nested CSS for more than 7 years -</small> and also because I like to keep all my rules on the same line <small>(easier to find proper selectors and editing properties isn&#8217;t that common)</small></p>
<h3>Sum up</h3>
<p>These tools have some cool features like the helper functions for color manipulation, variables, math helpers, logical operators, etc, but I honestly don&#8217;t think it would improve my workflow that much.</p>
<p>My feeling for these pre-processors is the same feeling I have for CoffeeScript, nice syntax and features but too much overhead for no &#8220;real&#8221; gain. Syntax isn&#8217;t the real problem in JavaScript for me the same way that it isn&#8217;t the real problem in CSS <small>(and most of the languages)</small>. You still need to understand how the box-model works, specificity, cascading, selectors, floats, browser quirks, etc&#8230; you are just adding another layer of abstraction between you and the interpreted stylesheet, adding yet another barrier for future developers and increasing the chance of over-engineering. Markup may become simpler <small>(with less classes/ids)</small> but it comes with many drawbacks.</p>
<p>For me <strong>the greatest problem are developers that code CSS without the knowledge required to build a maintainable and scalable structure.</strong> A stylesheet full of mixins, if/else, loops, variables, functions, etc, will be as hard to maintain as a bloated hand-crafted stylesheet, if not harder. Developers have an inherited desire to be &#8220;clever&#8221; and that is usually a <em>red flag</em>.</p>
<blockquote><p>
  <em>“Everyone knows that debugging is twice as hard as writing a program in the first place. So if you’re as clever as you can be when you write it, how will you ever debug it?”</em> – Brian Kernighan
</p></blockquote>
<p>Mixins are popular nowadays because of browser vendor prefixes, the real problem isn&#8217;t that CSS doesn&#8217;t support mixins or variables natively but that we have to write an absurd amount of vendor prefixes for no real reason since most of the implementations are similar and most of the features are only &#8220;cosmetic&#8221;. The real issue isn&#8217;t the language syntax, but the way that browsers are adding new features and people using them before they are implemented broadly <small>(without prefixes)</small>. &#8211; This could be handled by a pre-processor that only adds the vendor prefixes <small>(without the need of mixins or a special language)</small> like <a href="http://cssprefixer.appspot.com/">cssprefixer</a>. <strong>Try to find what is the real problem you are trying to solve and think about different solutions.</strong></p>
<blockquote><p>
  <em>&#8220;It’s time to abolish all vendor prefixes. They’ve become solutions for which there is no problem, and they are actively harming web standards.&#8221;</em> &#8211; Peter-Paul Koch
</p></blockquote>
<p>I&#8217;ve been following the <a href="https://github.com/stubbornella/oocss/wiki/faq">OOCSS</a> approach on most of my latest projects, and probably will keep doing it until I find a better approach. For the kind of stuff I&#8217;m coding it is more important to be able to code things fast and make updates during the development phase than to maintain/evolve the project over many months/years. I find it very unlikely to make drastic design changes without updating the markup, on the last 100 projects I coded it probably only happened 2 or 3 times. <small>- css zen garden is a cool concept but not really that practical -</small> Features like <code>desaturate(@red, 10%)</code> are cool but usually designers already provides me a color palette to be used on the whole site and I don&#8217;t duplicate the same value that much, if I do duplicate it everywhere than I can simply do a &#8220;find and replace&#8221; inside all the CSS files and call it a day, by using a function that generates a color <small>(which you have no idea which value it will be)</small> you can&#8217;t simply do a find and replace since you don&#8217;t know what is the value you are looking for on the source code <small>- I prefer to simply use a color picker&#8230;</small></p>
<p><strong>I know my experience is very different from most people so that&#8217;s why my approach is also different, your mileage may vary&#8230;</strong> If I ever need to use any of these tools it won&#8217;t be an issue <small>(I have no strong barrier against them)</small>, I just don&#8217;t think they will save me that much time right now that would outweigh the drawbacks. <strong>Pick the tools based on the project and your workflow</strong>, it isn&#8217;t because I listed a couple issues that you should discard using a pre-processor, for many cases it would be an awesome way of generating stylesheets, just think about the drawbacks and be responsible.</p>
<blockquote><p><em>&#8220;With great power comes great responsibility.&#8221;</em> &#8211; Uncle Ben to Peter Parker</p></blockquote>
<p><small>PS: I love CSS, for me it&#8217;s one of the most rewarding tasks on a website development, it&#8217;s like solving a hard puzzle&#8230;</small></p>
<h3>Further Reading</h3>
<ul>
<li><a href="http://www.w3.org/People/Bos/CSS-variables">Why &#8220;variables&#8221; in CSS are harmful by Bert Bros</a> <small>(external)</small></li>
<li><a href="http://www.joelonsoftware.com/articles/LeakyAbstractions.html">The Law of Leaky Abstractions by Joel Spolsky</a> <small>(external)</small></li>
<li><a href="http://blakehaswell.wordpress.com/2011/12/28/less-sass-more-oocss/">LESS Sass. More OOCSS by Blake Haswell</a> <small>(external)</small></li>
<li><a href="http://blog.millermedeiros.com/2010/09/there-is-no-spoon/">There is no spoon</a></li>
<li><a href="http://blog.millermedeiros.com/2010/06/how-i-structure-css-files/">How I structure CSS files</a></li>
<li><a href="http://blog.millermedeiros.com/2011/07/pragmatic-css-using-js-and-inline-styles/">Pragmatic CSS: using JS and inline styles</a></li>
</ul>
<p><ins datetime="2011-11-09T14:49:31+00:00"><strong>Edit 2011/11/09:</strong> added link to &#8220;The law of leaky abstractions&#8221;, small tweaks to the copy and formatting.</ins><br />
<ins datetime="2012-02-04T15:04:09+00:00"><strong>Edit 2012/02/04:</strong> add link to &#8220;LESS Sass. More OOCSS.&#8221; to the further reading.</ins></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.millermedeiros.com/the-problem-with-css-pre-processors/feed/</wfw:commentRss>
		<slash:comments>48</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  blog.millermedeiros.com/feed/ ) in 0.81812 seconds, on May 19th, 2012 at 6:22 am UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on May 19th, 2012 at 7:22 am UTC -->
