<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>damianfral's blog</title>
    <link href="http://damianfral.github.io/blog/atom.xml" rel="self" />
    <link href="http://damianfral.github.io/blog" />
    <id>http://damianfral.github.io/blog/atom.xml</id>
    <author>
        <name>Damián Franco Álvarez</name>
        <email>huevofritopamojarpan@gmail.com</email>
    </author>
    <updated>2014-01-18T00:00:00Z</updated>
    <entry>
    <title>Alternatives to JavaScript (I)</title>
    <link href="http://damianfral.github.io/blog/posts/2014-01-18-alternatives-to-js.html" />
    <id>http://damianfral.github.io/blog/posts/2014-01-18-alternatives-to-js.html</id>
    <published>2014-01-18T00:00:00Z</published>
    <updated>2014-01-18T00:00:00Z</updated>
    <summary type="html"><![CDATA[<h1 class="article-title">
	Alternatives to JavaScript (I)
</h1>

<article>
	<div class="date">
		Posted on 18/01/2014
	</div>
	<p>JavaScript is the most ubiquitous computing runtime in the world. Web browsers are, by far, the most common host environments for JavaScript, probably followed by server platforms (see <a href="http://nodejs.org/">Node.js</a>). But JavaScript engines are embedded in many other tools; from microcontrollers, like Espruino, to graphical shells like GNOME Shell; from PDF documents to graphic editing programs, like Adobe Photoshop.</p>
<p>As I wrote in my <a href="2013-06-27-whats-wrong-with-you-javascript.html">first post</a> on this blog, JavaScript has some design problems and, in my opinion, these problems make large application development really hard.</p>
<p>So, as it’s pointed at <a href="http://www.haskell.org/haskellwiki/The_JavaScript_Problem">http://www.haskell.org/haskellwiki/The_JavaScript_Problem</a>, JavaScript sucks but we need JavaScript. As a result various alternative languages compiling to JavaScript and compilers for old language that generate JavaScript have emerged.</p>
<p>To see a a good list of languages and compilers that target JavaScript, visit <a href="https://github.com/jashkenas/coffee-script/wiki/List-of-languages-that-compile-to-JS">https://github.com/jashkenas/coffee-script/wiki/List-of-languages-that-compile-to-JS</a>. There are more than 200!</p>
<p>The process of <em>running another language</em> in a JavaScript interpreter is simplified if the developer tools for that platform support <a href="http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/?redirect_from_locale=es">source maps</a>, which maps the generated JavaScript to the original code. This way, you can debug, optimize, test… using the original code. This doesn’t mean you can forget or avoid learning JavaScript; in the end, JavaScript engines work with JavaScript.</p>
<h1 id="new-languages-that-target-javascript">New languages that target JavaScript</h1>
<p>I put in this section three languages with different <em>tastes</em> that have been developed to generate JavaScript code, licensed under open-source licenses and that I would consider to use.</p>
<p>These new languages are pretty different, CoffeeScript might remind you Python and Ruby, TypeScript is really influenced by Java, while PureScript belongs to the Haskell school. All they produce small (ready for client-side development) and readable code, so, don’t be afraid and give them a try to see if they fit your needs; if you want to return to JavaScript, just use the generated JavaScript.</p>
<h2 id="coffeescript">CoffeeScript</h2>
<p>The most popular alternative to JavaScript is <a href="http://coffeescript.org/">CoffeeScript</a>, in fact, At <a href="https://twitter.com/Quobis">Quobis</a>, we use CoffeeScript instead of JavaScript. His creator, <a href="https://twitter.com/jashkenas">Jeremy Ashkenas</a> (also the creator of <a href="http://backbonejs.org/">Backbone.js</a> and <a href="http://underscorejs.org/">Underscore.js</a>) says:</p>
<blockquote>
<p>CoffeeScript is a little language that compiles into JavaScript. Underneath that awkward Java-esque patina, JavaScript has always had a gorgeous heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.</p>
</blockquote>
<p>CoffeeScript is just a syntactic sugar layer over JavaScript inspired, mostly, by Python and Ruby. Hence, it’s just another syntax for writting JavaScript code. It avoids some JavaScript pitfalls and adds some features like <em>sort of</em> object-oriented programming via classes, implicit returns, list comprehensions or postfix operators for loops and conditionals.</p>
<p>Its main advantage is, at the same time, its bigger drawback: it’s just a saner way to write JavaScript code, but it’s JavaScript. Actually, the golden rule of CoffeeScript is <em>It’s just JavaScript</em>.</p>
<p>It is worth pointing out there a good bunch of CoffeeScript forks and dialects with different goals like <a href="https://github.com/satyr/coco">Coco</a>, that aims to be more radical, or <a href="http://maxtaco.github.io/coffee-script/">IcedCoffeeScript</a>, which is a superset of CoffeeScript that adds some keywords to deal with asynchronows control flow.</p>
<h2 id="typescript">TypeScript</h2>
<p><a href="http://www.typescriptlang.org/">TypeScript</a> is a Microsoft project that adds structural typing on top of JavaScript:</p>
<blockquote>
<p>TypeScript is a language for application-scale JavaScript development. TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.</p>
</blockquote>
<p>You can think on TypeScript as JavaScript plus optional static types and class-based object-oriented programming; so, TypeScript provides support for classes, properties, inheritance, interfaces and namespaces. By default, TypeScript delegates to dynamic typing (type <code>any</code>) when it can’t find the type out. So, valid JavaScript code is valid TypeScript code too.</p>
<p>The TypeScript compiler has a flag, <code>--noImplicitAny</code>, which fires a warning on untyped expressions and declarations. There is <a href="https://github.com/borisyankov/DefinitelyTyped">a repository in github</a> where you can find TypeScript type definitons for more thab 300 JavaScript libraries and APIs.</p>
<h2 id="purescript">PureScript</h2>
<p><a href="https://github.com/paf31/purescript">PureScript</a> is a <a href="https://twitter.com/paf31">Phil Freeman</a>’s project. PureScript is a rewording of JavaScript with a strongly type system in the style of Haskell type system. In the words of its creator:</p>
<blockquote>
<p>I was looking for a simple functional language which would compile to JavaScript and have the following characteristics:</p>
<ul>
<li>Generates simple readable Javascript</li>
<li>Provides the ability to compile to tight loops if necessary</li>
<li>Reasonable type system</li>
<li>Ideally, written in a programming language I would enjoy working in</li>
<li>Provides a simple interface to existing Javascript code</li>
</ul>
<p>PureScript is not designed to be a general-purpose programming language. The primary use case is as a generator for purely-functional core libraries, with the main application code written in another language.</p>
</blockquote>
<p>A look to PureScript code shows is clearly inspired by Haskell. As Haskell, it provides algebraic datatypes, homogeneous arrays, polimorphic types, type inference, typeclasses, pattern matching… If you are a Haskeller, you likely want to try PureScript.</p>
<p>The main problem with PureScript is, contrary to what happens to TypeScript, the absent of wrappers for most common JavaScript libraries. It provides a simple Foreign Function Interface that allows you to write wrappers by yourself. This language is neither popular enought nor supported by a big company. I hope that PureScript will increase its community, so, this problem will be a matter of time.</p>
</article>]]></summary>
</entry>
<entry>
    <title>A command-line todo list manager written in Haskell</title>
    <link href="http://damianfral.github.io/blog/posts/2013-12-30-th.html" />
    <id>http://damianfral.github.io/blog/posts/2013-12-30-th.html</id>
    <published>2013-12-30T00:00:00Z</published>
    <updated>2013-12-30T00:00:00Z</updated>
    <summary type="html"><![CDATA[<h1 class="article-title">
	A command-line todo list manager written in Haskell
</h1>

<article>
	<div class="date">
		Posted on 30/12/2013
	</div>
	<h1 id="th">th</h1>
<p>th is a command-line todo list manager in the style of <a href="http://stevelosh.com/projects/t/">t</a> written in Haskell.</p>
<p>th shares with <a href="http://stevelosh.com/projects/t/">t</a> the same features:</p>
<ul>
<li>It’s simple.</li>
<li>It just uses a <em>human readable</em> plain file.</li>
<li>It works nicely with Dropbox, control version systems and shell scripts.</li>
</ul>
<h2 id="installing-th">Installing th</h2>
<p>th requires <a href="http://www.haskell.org/platform/index.html">Haskell Platform</a> and a UNIX-like shell (I use zsh). It may work on Linux, OS X and Windows (using <a href="http://www.cygwin.com/">Cygwin</a>).</p>
<p>Once you have installed <a href="http://www.haskell.org/platform/index.html">Haskell Platform</a>, you have to <a href="https://github.com/damianfral/th/archive/master.zip">download</a> the latest version or clone the repository using git, <code>git clone https://github.com/damianfral/th.git</code>.</p>
<p>Having the repository downloaded/clone, you just need to execute <code>cabal install</code>. You may set up your path to be able to access <code>~/.cabal/bin/</code> without the absolute path.</p>
<h2 id="using-th">Using th</h2>
<p>You can execute <code>th -h</code> to show the usage information:</p>
<pre><code>&gt; th -h

Usage: th [OPTION...]
  -v, -V       --version          Show the version of th
  -h, -H       --help             Show help for th
  -c TASKNAME  --create=TASKNAME  Create a new task
  -s TASKID    --start=TASKID     Mark task as started
  -f TASKID    --finish=TASKID    Mark task as finished
  -d TASKID    --delete=TASKID    Delete task
  -l FILENAME  --list=FILENAME    Use this file as the task list</code></pre>
<p>By default, if you don’t specify a file with <code>--list</code>, th will use <code>todo.txt</code>.</p>
<p>Each task can be in one of these 3 states: <em>not done</em>, <em>started</em>, <em>finish</em>.</p>
<h3 id="create-tasks">Create tasks</h3>
<pre><code>&gt; th -c &quot;Release version v1.6&quot;

1 - [ ] Release version v1.6


&gt; th -c &quot;Review open issues&quot;

1 - [ ] Release version v1.6
2 - [ ] Review open issues</code></pre>
<h3 id="startfinish-a-task">Start/Finish a task</h3>
<pre><code>&gt; th -s 1

1 - [-] Release version v1.6
2 - [ ] Review open issues

&gt; th -f 1

1 - [x] Release version v1.6
2 - [ ] Review open issues</code></pre>
<h3 id="delete-a-task">Delete a task</h3>
<pre><code>&gt; th -d 1

1 - [ ] Review open issues</code></pre>
<h3 id="show-tasks">Show tasks</h3>
<pre><code>&gt; th

1 - [ ] Review open issues</code></pre>
</article>]]></summary>
</entry>
<entry>
    <title>Noise reduction in images through HDR fusion in the Bayer domain</title>
    <link href="http://damianfral.github.io/blog/posts/2013-09-25-noise-reduction-hdr-fusion-bayer-domain.html" />
    <id>http://damianfral.github.io/blog/posts/2013-09-25-noise-reduction-hdr-fusion-bayer-domain.html</id>
    <published>2013-09-25T00:00:00Z</published>
    <updated>2013-09-25T00:00:00Z</updated>
    <summary type="html"><![CDATA[<h1 class="article-title">
	Noise reduction in images through HDR fusion in the Bayer domain
</h1>

<article>
	<div class="date">
		Posted on 25/09/2013
	</div>
	<h1 id="introduction">Introduction</h1>
<p>This is a brief post about my final year project in computer engineering. I’ve developed a small command line application to do high dynamic range fusion on RAW images (Bayer domain). I’ve coded it in C++ using <a href="http://halide-lang.org/">Halide</a> and <a href="http://www.libraw.org/">LibRaw</a>.</p>
<p>This little application takes some RAW files, 2 or more, as input and returns a HDR TIFF image.</p>
<p>RAWs I’ve used to get the images showed in this post belongs to <a href="http://kelbytraining.com/product/the-hdr-book-unlocking-the-pros-hottest-post-processing-techniques-2/">The HDR Book: Unlocking the Pros Hottest Post-Processing Techniques</a> (I haven’t read it).</p>
<h1 id="noise-measurement">Noise measurement</h1>
<p>If we take a photography of an <em>uniform zone</em> with an ideal camera all pixels in the image will have the same value. But the perfect camera does not exist. This image will always have some interference, noise, that will break the uniformity making pixels fluctuate around a value, the mean value. So, we can equate average value with noiseless value and standard deviation with noise. Hence, we can express signal to noise ratio (SNR) this way:</p>
<p><math display="block" xmlns="http://www.w3.org/1998/Math/MathML"><mrow><mi>S</mi><mi>N</mi><mi>R</mi><mo stretchy="false">(</mo><mi>i</mi><mi>m</mi><mi>a</mi><mi>g</mi><mi>e</mi><mo stretchy="false">)</mo><mo>=</mo><mfrac><mrow><mi>μ</mi><mo stretchy="false">(</mo><mi>i</mi><mi>m</mi><mi>a</mi><mi>g</mi><mi>e</mi><mo stretchy="false">)</mo></mrow><mrow><mi>σ</mi><mo stretchy="false">(</mo><mi>i</mi><mi>m</mi><mi>a</mi><mi>g</mi><mi>e</mi><mo stretchy="false">)</mo></mrow></mfrac></mrow></math></p>
<p>We can meassure the SNR for different relative exposures by taking some pictures to an uniform zone (using the manual focus to blur the image in order to avoid textures) with different exposure times.</p>
<p><img src="../images/2013-09-25-noise-reduction-hdr-fusion-bayer-domain/snr.png" /></p>
<h1 id="hdr-fusion">HDR fusion</h1>
<p>Reading the previous chart we realize we need to increase exposure, <a href="http://en.wikipedia.org/wiki/Exposing_to_the_right">exposing to the right</a> if we want to get less noise. But there is a limit, the saturation point. This is the point at which it can no longer generate new electrons for additional photon strikes.</p>
<p>We could take two photos, one well-exposed and another one overexposed. The well-exposed picture will have detail in the highlights but more noise than the overexposed picture. The overexposed image will have the opposite features, much less noise and saturated highlights. Equalising the exposure level and taking the best parts of each image (the highlight from the well-exposed picture, the non-saturated parts form the overexposed one) we can get a image with higher dynamic range and less noise. This is called High Dynamic Range fusion.</p>
<h1 id="fusion-map">Fusion Map</h1>
<p>The key to get a fused HDR image with lower noise is in the generation of the fusion map. In the case of two input images, this approach binarizes the more exposed picture with the next formula to get a fusion map where pixels with value 0 are fitted with the well-exposed picture, and pixel with value 1, with the over-exposed one:</p>
<p><math display="block" xmlns="http://www.w3.org/1998/Math/MathML"><mrow><mi>m</mi><mi>a</mi><mi>p</mi><mo stretchy="false">(</mo><mi>x</mi><mo>,</mo><mi>y</mi><mo stretchy="false">)</mo><mo>=</mo><mi>o</mi><mi>v</mi><mi>e</mi><mi>r</mi><mi>e</mi><mi>x</mi><mi>p</mi><mi>o</mi><mi>s</mi><mi>e</mi><mi>d</mi><mo stretchy="false">(</mo><mi>x</mi><mo>,</mo><mi>y</mi><mo stretchy="false">)</mo><mo>≤</mo><mo stretchy="false">(</mo><mi>s</mi><mi>a</mi><mi>t</mi><mi>u</mi><mi>r</mi><mi>a</mi><mi>t</mi><mi>i</mi><mi>o</mi><mi>n</mi><mo>⋅</mo><mi>t</mi><mi>h</mi><mi>r</mi><mi>e</mi><mi>s</mi><mi>h</mi><mi>o</mi><mi>l</mi><mi>d</mi><mo stretchy="false">)</mo></mrow></math></p>
<p>The above formula has a threshold value between 0 and 1 to take more (higher threshold) or less (lower value) highlights from de overexposed image. The binarized image is blurred with Guassian kernel to avoid sudden transitions in the final image.</p>
<p>Extending this process to support more than two images is pretty simple.</p>
<div class="flex-row flex-images">

	<div>
		<img src="../images/2013-09-25-noise-reduction-hdr-fusion-bayer-domain/test7-0EV.jpeg">
	</div>
	<div>
		<img src="../images/2013-09-25-noise-reduction-hdr-fusion-bayer-domain/test7-2EV.jpeg">
	</div>
	<div>
		<img src="../images/2013-09-25-noise-reduction-hdr-fusion-bayer-domain/test7-4EV.jpeg">
	</div>
</div>

<div class="flex-row flex-images">
	<div>
		<img src="../images/2013-09-25-noise-reduction-hdr-fusion-bayer-domain/map7.jpeg">
	</div>
	<div>
		<img src="../images/2013-09-25-noise-reduction-hdr-fusion-bayer-domain/test7-tm.jpeg">
	</div>
 </div>
<h1 id="bayer-domain">Bayer Domain</h1>
<p>There is a diference between my application and common approaches, it uses directly RAW images. A RAW image contains only one channel per pixel (R,G or B). So, while other aplications use raster images, which have one real and two interpolated channels, this application only works with real data. This way, the performance may be improved.</p>
<h1 id="noise-reduction">Noise reduction</h1>
<p>The level of noise reduction depends on the exposure schema. A scheme like [0 EV, +3 EV, +6 EV] works pretty well. A wider exposure scheme can increase the noise reduction, but it could generate artifacts (visible fusion borders) due to the difference SNR between pixels from photos with a high exposure level difference.</p>
<div class="flex-row flex-images">
	<div>
		<img 	src="../images/2013-09-25-noise-reduction-hdr-fusion-bayer-domain/0EV-detail.jpeg">
	</div>
	<div>
		<img src="../images/2013-09-25-noise-reduction-hdr-fusion-bayer-domain/hdr-detail.jpeg">
 	</div>
 </div>
<h1 id="tonemapping">Tonemapping</h1>
<p>This application uses the less exposed photography as reference, so the fusion result has the same look. This way we can avoid the <a href="http://en.wikipedia.org/wiki/Tone_mapping">tonemapping</a> process. Nevertheless, by applying a tonemapping operator we can get a better result if the less exposed image is <em>too</em> underexposed. Anyway, this application does not include a tonemapping option, but the user could use an external tool like <a href="http://pfstools.sourceforge.net/pfstmo.html">pfstmo</a>.</p>
<h1 id="next-steps">Next steps</h1>
<p>I may open source this application in the future. But, firstly, I want to change some parts an fix some bugs. If someone want me to explain this project more deeply or something about digital photography or image processing, just ask it.</p>
<h1 id="thanks">Thanks</h1>
<p>I would like to thank some people for their support. In the first place, I want to express my gratitude to my girlfriend, <a href="https://twitter.com/angelagesteiras">Ángela</a>, for all those hours in the library and for her photographies, advices and help. Next, I want to mention <a href="http://www.guillermoluijk.com/">Guillermo Luijk</a>, his work on digital photography is the base of this project. I also want to thank <a href="https://twitter.com/quobis">Quobis</a>, the company I work for (they have been unselfish and gave me the posibility to shift my working schedule), and my friends <a href="https://twitter.com/ATuin">Aitor</a> and <a href="https://twitter.com/EleDiaz777">Eleazar</a> for encouraging me.</p>
</article>]]></summary>
</entry>
<entry>
    <title>Simple Monads Example (CoffeeScript)</title>
    <link href="http://damianfral.github.io/blog/posts/2013-07-07-simple-monads-example.html" />
    <id>http://damianfral.github.io/blog/posts/2013-07-07-simple-monads-example.html</id>
    <published>2013-07-07T00:00:00Z</published>
    <updated>2013-07-07T00:00:00Z</updated>
    <summary type="html"><![CDATA[<h1 class="article-title">
	Simple Monads Example (CoffeeScript)
</h1>

<article>
	<div class="date">
		Posted on 07/07/2013
	</div>
	<p>This article is based on <a href="http://www.intensivesystems.net/tutorials/why_monads.html">Why use monads</a>.</p>
<p>Suppose you have some functions that take a number and answer another number or <em>null</em>:</p>
<pre class="sourceCode Coffeescript"><code>inc = (x) -&gt;
    if x isnt 6
        x + 1
    else
        null

double = (x) -&gt;
    if x % 2
        x * 2
    else
        null

dec = (x) -&gt;
    if x isnt 3
        x - 1
    else
        null</code></pre>
<p>Now, you want to compose a new function chaining previous functions. Something like this:</p>
<pre class="sourceCode Coffeescript"><code>all = (x) -&gt;
    dec(double(inc(x)))</code></pre>
<p>This is not the most elegant way of chaining functions, so you write a <em>generic chain</em> function:</p>
<pre class="sourceCode Coffeescript"><code>chain = (funcs...) -&gt;
    (arg) -&gt;
        for func in funcs
            arg = func arg
        return arg

all = chain dec, double, inc
all 3 # Wrong result: 3. Expected result: null</code></pre>
<p>In spite of being a better path, you still have to deal with null values or otherwise we will see things like last line of the above code (in JavaScript <em>null</em> plus 1 is 1). You could change previous chaining function in order to be specific for this problem or create new all function that stops running and returns null when a <em>chained</em> function returns <em>null</em>:</p>
<pre class="sourceCode Coffeescript"><code>all = (x) -&gt;
    return null if tmp is null
    tmp = inc x
    return null if tmp is null
    tmp = double tmp
    return null if tmp is null
    tmp = dec tmp
    return tmp</code></pre>
<p>There is a clear pattern there; these functions are monadic functions under the <strong>maybe monad</strong>, we can combine them like this <sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup>:</p>
<pre class="sourceCode Coffeescript"><code>all = doMonad MaybeMonad, inc, double, dec
all null # null
all 3    # null
all 8    # 17</code></pre>
<p>Other languages like Haskell allow this kind of composition without effort. In JavaScript (or CoffeeScript) we have to work a little more to get it:</p>
<pre class="sourceCode Coffeescript"><code>None       = null
MaybeMonad =
    mReturn: (value) -&gt;
        if value in [undefined, null, NaN]
            return None
        return value

    mBind: (value, f) -&gt;
        return None if value is None
        return f value



doMonad = (monad, funcs...) -&gt;
    (result) -&gt;
        iterator = (i = 0) -&gt;
            if i is funcs.length
                return monad.mReturn result
            else
                result   = funcs[i] result
                return monad.mBind result, -&gt; iterator i + 1

        return monad.mBind (monad.mReturn result), -&gt; iterator 0</code></pre>
<p>What the hell do we have here? It easier than it seems. There is a <em>None</em> variable, a <em>MaybeMonad</em> associative array and a doMonad function. The MaybeMonad has 2 functions.</p>
<ul>
<li><strong>mReturn</strong> takes a value and transform it (or maybe not).</li>
<li><strong>mBind</strong> takes a value (it will be always returned by mReturn) and a function and do some computations to call that function (or maybe not).</li>
</ul>
<p>The doMonad functions takes a monad and a bunch of functions (funcs) and returns a new function. This function will receive an argument (result) and it will iterate over funcs to call them with the value returned for the previous function as argument except for the first function (it has not previous function) that receives the same argument, called result, as the wrapper function. The special thing here is that these iterative execution of functions are <em>proxied</em> with monad.mBind. In the case of MaybeMonad, mBind decides if the next function will be executed or not.</p>
<p>The point is doMonad is generic and you can write your own monads to composing functions with your own pattern. Let’s see the List monad:</p>
<pre class="sourceCode Coffeescript"><code>flatten = (value) -&gt;
    if Array.isArray value
        output = []
        value.map (elem) -&gt;
            if Array.isArray elem
                output = output.concat flatten elem
            else
                output.push elem
        return output
    else
        return [value]</code></pre>
<p>In this case, <em>mBind</em> doesn’t stops the chained executions, but just flats the returned array received as argument. We can get this:</p>
<pre class="sourceCode Coffeescript"><code>ListMonad =
    mBind: (list, f) -&gt;
        output = list.map f
        return flatten output

    mReturn: (value) -&gt;
        return [value]


replicate = (n) -&gt;
    (v) -&gt; [0...n].map -&gt; v

generation = (value) -&gt; (replicate 3) value

f = doMonad ListMonad, generation, generation
f [&quot;No God! Please no!&quot;]

# [ &#39;No God! Please no!&#39;,
#   &#39;No God! Please no!&#39;,
#   &#39;No God! Please no!&#39;,
#   &#39;No God! Please no!&#39;,
#   &#39;No God! Please no!&#39;,
#   &#39;No God! Please no!&#39;,
#   &#39;No God! Please no!&#39;,
#   &#39;No God! Please no!&#39;,
#   &#39;No God! Please no!&#39; ]</code></pre>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Copy-pasted sentence.<a href="#fnref1">↩</a></p></li>
</ol>
</div>
</article>]]></summary>
</entry>
<entry>
    <title>What's wrong with you, JavaScript?</title>
    <link href="http://damianfral.github.io/blog/posts/2013-06-27-whats-wrong-with-you-javascript.html" />
    <id>http://damianfral.github.io/blog/posts/2013-06-27-whats-wrong-with-you-javascript.html</id>
    <published>2013-06-27T00:00:00Z</published>
    <updated>2013-06-27T00:00:00Z</updated>
    <summary type="html"><![CDATA[<h1 class="article-title">
	What's wrong with you, JavaScript?
</h1>

<article>
	<div class="date">
		Posted on 27/06/2013
	</div>
	<h1 id="prototypal-object-orientation">Prototypal Object Orientation</h1>
<p>Class-based object orientation is the most used approach to object orientation. <strong>JavaScript is the only mainstream language that has prototypes</strong>. I don’t want to say which one is better, just that I feel more confortable with classes. JavaScript prototypes can emulate class systems. In fact, there are many libraries for that.</p>
<h1 id="modules-and-var-declaration">Modules and Var declaration</h1>
<p><strong>JavaScript has no formal construct for namespaces</strong>. Module pattern (passing the namespace as an argument to an anonymous self-invoking function) is really helpful. Lexical scope and closures are nice, which allows the module pattern, but something as important as namespaces must be part of the language, don’t you think?</p>
<p>Another weird behaviour is related to the var keyword. If you declare a variable with var, it will belong to the local scope. If you don’t, its scope will be global with overwritting problems and performance penalty (the interpreter will look up the scope chain to find the global variable).</p>
<h1 id="syntax">Syntax</h1>
<p>Event driven code is really common in JavaScript. Usually, if you don’t use promises or some stuffs like <a href="http://noflojs.org/">Flow-Based Programming</a> (FBP), you define a callback that is passed as argument to a function that binds that function to an event, like DOM events in the browser or EventEmitter events in Nodejs. So, when you have a callback that binds another callback to another event that binds another callback to… and enclosed by the module pattern, you will see something like this:</p>
<pre class="sourceCode Javascript"><code class="sourceCode javascript">(<span class="kw">function</span>()
{
    <span class="fu">$</span>(<span class="st">&quot;#my-button1&quot;</span>).<span class="fu">on</span>(<span class="st">&quot;click&quot;</span>, <span class="kw">function</span>(msg1)
    {
        <span class="fu">alert</span>(msg1);
        <span class="fu">$</span>(<span class="st">&quot;#my-button2&quot;</span>).<span class="fu">on</span>(<span class="st">&quot;click&quot;</span>, <span class="kw">function</span>(msg2)
        {
            <span class="fu">alert</span>(msg2);
            <span class="fu">$</span>(<span class="st">&quot;#my-button3&quot;</span>).<span class="fu">on</span>(<span class="st">&quot;click&quot;</span>, <span class="kw">function</span>(msg3)
            {
                <span class="fu">alert</span>(msg3);
            });
        });
    });
}).<span class="fu">call</span>(<span class="kw">this</span>);</code></pre>
<p>I prefer indentation over braces and parenthesis, so the above code looks pretty ugly for me.</p>
<h1 id="dynamic-typing-and-late-binding">Dynamic typing and late binding</h1>
<p>Delaying type-checking to runtime is nice for fast-prototyping and data intensive applications (generating types and behaviours based on runtime data). Not so many years ago, JavaScript was used as a toy language to add some animations, form validations and simple stuffs. AJAX changed it all. JavaScript has been growing up since then and nowadays it is used in bigger apps (databases, game engines, communications apps, multimedia apps..) that may have a high cyclomatic complexity. Since JavaScript just checks types and binds names in runtime, a stupid unnoticed error misnaming a variable or a method could slap your face in the worst moment (<em>demo effect</em>).</p>
<div class="flex-images">
    <img src="http://i.imgur.com/tYrpOT3.gif">
</div>
<p>Static typing is not the holy grail, but it is <strong>safer</strong>. Haskell guys, as <a href="https://twitter.com/EleDiaz777">@EleDiaz</a> , know that if Haskell code compiles, it is almost certain that it will work as expected.</p>
<p>And some web applications need performance. Doing some tasks in the compilation time (AOT), can give us, for example, a higher FPS value in our game.</p>
<h1 id="weak-typing">Weak typing</h1>
<p>Coercion plus dynamic typing results on a <strong><em>debugging hell</em></strong>. Many JavaScript programmers, I guess, have noticed that debugging JavaScript code is not easy. Many errors are hidden by implicit conversions. It might speed up development (in my opinion, it’s just true in the case of small apps; bigger applications require safety), but it slows down debugging by a higher factor.</p>
<h1 id="surprise-behaviour">Surprise behaviour</h1>
<p>JavaScript is a joker. Let’s see:</p>
<pre class="sourceCode Javascript"><code class="sourceCode javascript"><span class="kw">var</span> a = (<span class="dv">7</span>, <span class="dv">5</span>); <span class="co">// -&gt; a = 5</span>
<span class="kw">typeof</span>({} + []) <span class="co">// -&gt; &quot;string&quot;</span>
<span class="kw">typeof</span>([] + {}) <span class="co">// -&gt; &quot;number&quot;</span>

<span class="st">&quot;1&quot;</span> &gt;= -<span class="kw">Infinity</span> <span class="co">// true</span>
<span class="st">&quot;A&quot;</span> &gt;= -<span class="kw">Infinity</span> <span class="co">// false</span>
<span class="st">&quot;A&quot;</span> &lt; -<span class="kw">Infinity</span>  <span class="co">// false</span></code></pre>
<p>Despite of the fact that ES 6 has some new proposals to minify or solve these and other <em>problems</em>, there is another path to avoid them: use another programming language that targets JavaScript.</p>
<p>There are some new languages that try to hide the bad parts adding a syntax sugar layer keeping the JavaScript semantics. Other languages have a completely new syntax and semantics. And there is another option, compilers for <em>old</em> languages that generate JavaScript code.</p>
</article>]]></summary>
</entry>

</feed>
