ciplogic.com
Live with grace. Write superb software.

programming

  • core-lang: Better Collection Classes for JavaScript

    It brings me great joy to announce the release of version 1.0.0 of core-lang, the collection classes I wrote for JavaScript.

    Overview

    With an API that is fully compatible with the JavaScript API, keeping the same signatures and behaviors for functions such as forEach, etc, but also inspired from groovy, having methods such as groupBy, chaining support, and full Promise support, allowing to deal with collections that contain promises, or are transformed to promises, using simple chainable calls.

  • fast-live-reload Presentation

    When creating web applications, a lot of time is consumed switching back and forth between the code and the application itself. What if there would be an application that would refresh your browsers automatically?

  • JavaScript Exception Error Logging Pattern

    Many times in JavaScript, I like to log errors in case exceptions happen, that output what exactly went wrong, without actually taking action.

    For example:

    1
    2
    3
    4
    5
    6
    try {
      callPotentialDangerousStuff();
    } catch (e) {
      console.error("dangerous stuff is not working :(");
      throw e;
    }

    This has the side effect of loosing the stack trace if I break on "uncaught exceptions", and breaking on "all exceptions" is absolutely no option, since many frameworks use the exception handling as mechanisms of detecting various features of the browser environment.

    Thus I came up with this pattern:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    var executionSuccessful = false;
     
    try {
      callPotentialDangerousStuff();
      executionSuccessful = true;
    } finally {
      if (!executionSuccessful) {
        console.error("dangerous stuff is not working :(");
      }
    }

    So if an exception happens, I can still break on all exceptions, but also get my log right.

    Can you imagine how cool it would be to chain exceptions like in Java? For example:

    1
    2
    3
    4
    5
    6
    try {
      callPotentialDangerousStuff();
    } catch (e) {
      console.error("dangerous stuff is not working :(");
      throw new Error("dangerous stuff", e);
    }

    At least we can dream about it, and appreciate more languages that do offer chaining of exceptions.

  • JavaScript Exception Handling HowTo

    A very used paradigm when it come with dealing with errors is the try/catch construct.

    In JavaScript you can throw anything as an exception, and in your catch statement you will receive that object instance that you threw. This is pretty cool, because when you receive the catched object, it might contain valuable information on what actually went wrong. In most cases though people just pass a string with the error message.

    I've seen advanced programmers actually throwing the message itself as the thrown object, in code that I will simplify as this:

    1
    2
    3
    4
    5
    6
    7
    try {
        console.log("computer reports heating at engine 1.");
        throw "oh man, catastrophic failure at engine 1.";
    } catch (e) {
        console.log("last words were:", e);
        console.log('the time backtrack saving device took note of the missing ship.');
    }

    Output:

    1
    2
    3
    computer reports heating at engine 1.
    last words were: oh man, catastrophic failure at engine 1.
    the time backtrack saving device took note of the missing ship.

    Unfortunately this is a problem, since we got the error message, and it looks good in our 7 lines of code. In reality if our program was a bit bigger, our message was now meaningless, since we would need to find from where the thing was thrown. If the code that can cause the catastrophic failure is called from multiple sites, this only adds to the complexity.

    This is why you always use the Exception object. The Exception object is part of standard JavaScript, and in all browsers,Chrome, Firefox, and IE from version 10 onwards (no one uses IE9 on their space ship anyway) has an extra property, named stack, that gives you the stack trace:

    1
    2
    3
    4
    5
    6
    7
    8
    try {
        console.log("computer reports heating at engine 1.");
        throw new Error("oh man, catastrophic failure at engine 1.");
    } catch (e) {
        console.log(e.stack);
        console.error("the pilot warning message was:", e);
        console.log('the time backtrack saving device went back in time and send a bot to fix the engine.');
    }

    This gives the output:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    computer reports heating at engine 1.
    Error: oh man, catastrophic failure at engine 1.
       at window.onload (http://fiddle.jshell.net/_display/:26:5)
    the pilot warning message was: Error: oh man, catastrophic failure at engine 1.
       "the pilot warning message was:"
       {
          [functions]: ,
          description: "oh man, catastrophic failure at engine 1.",
          message: "oh man, catastrophic failure at engine 1.",
          name: "Error",
          stack: "Error: oh man, catastrophic failure at engine 1.
       at window.onload (http://fiddle.jshell.net/_display/:26:5)"
       }
       
    the time backtrack saving device went back in time and send a bot to fix the engine.

    So please always use Exception objects and avoid space ship tragedies.

  • Live reloading web pages using VIM

    Do you want to live reload the browser as you edit and save using VIM?

    Well wait no more, you can install the application by simply running:

    1
    2
    npm install -g fast-live-reload
    fast-live-reload

    Afterwards whenever saving, the page is automatically reloaded. Without any browser plugins.

    fast-live-reload in action

  • Native vs Bluebird vs Core-Promise Benchmark

    I just took for a test the native promises implementation (that is available since node v0.12), the bluebird implementation, and core-promise, my own TypeScript implementation.

    The tests are here for the native, bluebirdor core-promise. Note that all the implementations pass the full Promises/A+ test spectrum of 872 tests.

    I ran each test file 11 times, using:

    1
    for f in `seq 0 10`; do time mocha test-core-promise.js > /dev/null 2>&1; done

    Obviously, I changed the file name between iterations.

    I removed 11.9 seconds, because these are setTimeouts in the actual tests, remaining with actual execution of promises time, and these are the final results (in seconds):

     

    Native Bluebird Core-Promise

    1.616 1.760 1.564

    1.567 1.626 1.520

    1.568 1.669 1.548

    1.539 1.657 1.573

    1.574 1.595 1.557

    1.583 1.604 1.580

    1.543 1.582 1.540

    1.529 1.622 1.567

    1.600 1.605 1.567

    1.407 1.661 1.544

    1.467 1.640 1.587

     

    Conclusion

    Unsurprisingly the native implementation won performance wise, but only less than 1% compared to the core-promise, but ~5% compared to bluebird. Also core-promise defaults to the native promises implementation if it's available, if you would use the exported Promise class (for tests I accessed the CorePromise implementation on purpose).

    1
    var Promise = require("core-promise").Promise;

    Not to mention readability of code: core-promise's Promise vs bluebird's Promise.

    *Disclaimer* I am the creator of the core-promise, and yes I feel pretty good getting better performance than the "unmatched performance" of bluebird. :)

  • o=o YUI3 is Watching You

    Do you know why you would name a configuration object „o”?

    Because then you can write this:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
        /**
        Applies a new configuration object to the config of this YUI instance. This
        will merge new group/module definitions, and will also update the loader
        cache if necessary. Updating `Y.config` directly will not update the cache.
     
        @method applyConfig
        @param {Object} o the configuration object.
        @since 3.2.0
        **/
        applyConfig: function(o) {
     
            o = o || NOOP;
     
            var attr,
                name,
                // detail,
                config = this.config,

    Personally I would have preferred:

    1
        o= !o ?NOOP :o ; // note how many emotions are bundled in this code.

    But it looks amazing anyway, that o=o is looking straight into my developer soul.

    From here: https://github.com/yui/yui3/blob/master/src/yui/js/yui.js 

    PS: Why else would someone name an object variable "o"?

  • Pointy Thingie: The Linux Font Measuring Unit

    Since I don't want eye strain, and have a mild OCD, I want the same font and sizes across all the monospaced text editors that I am using.

    The font I decided in using is Ubuntu Mono with some patches to look good on my vim. It's a regular truetype font.

    Thus I went into the journey of setting it up across four applications (gvim, terminal, IDEA and VS Code).

    Turns out that IDEA and Visual Studio Code think that the font size should be 16 Pointy Thinigies, while GVim and the terminal would rather go for 12 Pointy Thingies, to render a text with the exact same size in pixels.

    Good job Linux.

  • Programming Vocabulary

    Whenever talking to each other, whenever that happens, developers tend to formalize specific concepts and map them to specific words.

    For example you all know what a singleton is. We don't need to disambiguate in regards to it. Nor do we need to disambiguate in regards to what an object, function, or method are.

    And this is why the following article A Factory Should Create, Not Retain, in which Paul M. Jones claims that a factory that retains references to its created instances it's not truly a factory, came as a surprise for me.

    The article TL;DR: A factory just creates objects, a registry just references objects, a container does both.

    Fine.

    But while this might be technically correct, it's not actually meaningful in any way to make this distinction, except tedious mental exercise. Don't worry, here come examples (Java, but, you get the picture).

     

    1. Caching factories are containers

    In java numbers can be represented as either primitives, either immutable objects. To convert from one another, e.g. from `int` to `Integer`, the Integer class has a factory function named: `valueOf(int) : Integer`. This makes the Integer class a factory for Integer objects.

    Except that I lied a bit.

    Creating objects for every number it's expensive, and since the low indexes are heavily used, they are pre-cached (at least in the Oracle's Java version they are). This is not part of the functional specification, it's just an implementation detail, on how the objects are going to be fetched. Note that objects outside that range are always created.

    http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Integer.java#Integer.valueOf%28int%29

    1
    2
    3
    4
    5
    6
    7
        public static Integer valueOf(int i) {
            final int offset = 128;
            if (i >= -128 && i <= 127) { // must cache
                return IntegerCache.cache[i + offset];
            }
            return new Integer(i);
        }

    Can you be pedantic and say, that this is a container, and not actually a factory? Yes. Does it add value to the conversation? No. I'm going later to explain why this is an issue.

    Note that if I just comment those caching lines, my container magically transforms to a factory, and if I uncomment it, it's back a container, even if functionally its behaviour is the same. But whatever.

    By the same definition...

     

    2. Registries that create objects are containers as well

    Again in java there is an amazing class, named TreeMap. TreeMap holds instances to these objects into a tree structure, thus its full of imagination name of TreeMap. Tree... Map. TreeMap.

    Someone could argue that this is a registry, but again, if we want to be pedantic about it, this is no ordinary registry. Because it creates its keys, so it's also a factory.

    http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/TreeMap.java#TreeMap.put%28java.lang.Object%2Cjava.lang.Object%29

    Among the many separation of concerns that this class blatantly violates, are also creating and reordering objects, but for the sake of our discution, we can safely say that the TreeMap is technically also a factory, since it creates its keys:

    1
    2
    3
    4
    5
          Entry<K,V> e = new Entry<K,V>(key, value, parent);
          if (cmp < 0)
              parent.left = e;
          else
              parent.right = e;

     

    3. Singleton

    Finally, I said that I will explain why I find it as an issue, with being pedantic about separation of concerns. Because it stiffles communication. We actually lose more time trying to disambiguate things that our so specific vocabulary would allegedly try to disambiguate.

    The best example is Singleton.

    Singleton it's a pattern that describes how single instances can be created for an application. This is made by having a single static instance on the class, and using it across the application.

    Except that this is not true if you use Dependency Injection. The singleton class will not have the single instance bound to the class. It will not implement the actual pattern. Actually might not even be a singleton in certain cases, since now this might be a configuration issue. So I should not use the "singleton" word to describe it at all, since it's not implementing the pattern, nor can I guarantee that it will always be a singleton.

    Conclusion

    But that's why this whole thing makes no sense. If I know that in my application an object has a single instance (provided by the DI, or its own static reference, or the JVM that creates it via some callback method, etc), then I can say it is a singleton. Its meaning is derived from its behavior, not the actual implementation on how the singleton behavior will be provided. That is an implementation detail.

    Similarily, if I have an object that creates other objects as one of its main purposes in life, it is a factory, irrespective on what kind of caching (if any it uses). It's meaningless to say that valueOf from Integer is actually a container method. There is no gained value out of it.

    If an object is used to mainly store references to other objects, then yes, it's a registry. The same goes on key creation. This doesn't changes the purpose of the class.

    It makes no sense looking at every tidbit of implementation details, with super categorization. There is no benefit out of it. No cleaner code, no better communication. Nothing.

    We can't see the forest anymore, since so many trees are blocking our view.

  • Stop Doing Double Negations

    Did your mind needs to stop to read (taken from ckeditor source):

    1
    2
    if ( !dontRemove )
        removeNoAttribsElement( element );

    Well you're not alone.

    Stop using double negations, even if your code looks "cleaner", and refactor them to be single negations.

    A simpler rule is never use negation variable names, so you don't run into issues like this. So don't use names such as: "noElementPresent", "dontRemove" or "notExisting".

    For the previous example instead of "don't remove" go with "keep element", "keep", or something along those lines. Just search a thesaurus if you can't find a word.

    1
    2
    if ( !keepElement )
        removeNoAttribsElement( element );

    Notice how readability is just so much better.

  • Sweet-Sweet JavaScript Debugging

    Who said dynamic languages can't be fun to debug?

  • TypeScript unit testing with Mocha

    I am writing some unit tests for my TypeScript collection classes (actually migrating some older tests), and I decided in going with Mocha.

    How easy it is? Well, as simple as 1, 2, 3... 4 :) :

    1. Install the typing files

    tsd install mocha
    tsd install node
    tsd install assert

    2. Write your test(s)

    For this example, I'm presenting you a super simple test, but obviously nothing stops you from adding new ones (check my github core-lang project for details):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    /// <reference path="../../../typings/mocha/mocha.d.ts"/>
    /// <reference path="../../../typings/node/node.d.ts"/>
    /// <reference path="../../../typings/assert/assert.d.ts"/>
     
    import { list, XIterable, XIterator } from "../../main/core/Iterable";
    import assert = require("assert");
     
    describe('ArrayList', function() {
        it('should allow filtering', function() {
            var items : XIterable<number> = list([1, 2, 3, 4]),
                filteredItems: XIterable<number>,
                iterator : XIterator<number>;
     
            filteredItems = items.filter(it => it % 2 == 0);
            iterator = filteredItems.iterator();
            
            assert.equal(iterator.next(), 2);
            assert.equal(iterator.next(), 4);
            assert.notEqual(iterator.hasNext(), true);
        });
    });

    3. Build your test(s)

    I use Grunt, so I have (I deleted all the non test stuff), but is basically easy to see the target that is named "test" across all the plugins in the original full Grunt file:

  • Vim AsciiDoc (or Markdown) Source Code Blocks Highlight

    Do you want your editing of AsciiDoc (or Markdown) to look like this?

    In order to get AsciiDoc support working nicely in VIM, you'll need a couple of things:

    • asciidoc-vim: (the syntax highlight support)
    • SyntaxRange: (to enable text ranges to be highlighted with different syntax files)
      • ingo-library: (not really documented, but this is a dependency for SyntaxRange)

    Then add another syntax file for AsciiDoc, by creating another plugin, with just the /syntax folder in it. (If you use pathogen, it should look something like this). In it configure your SyntaxRange plugin for matching for various languages:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    function! AsciidocEnableSyntaxRanges()
    " source block syntax highlighting
    if exists('g:loaded_SyntaxRange')
      for lang in ['c', 'python', 'vim', 'javascript', 'cucumber', 'xml', 'typescript', 'sh', 'java', 'cpp', 'sh']
        call SyntaxRange#Include(
              \  '\c\[source\s*,\s*' . lang . '.*\]\s*\n[=-]\{4,\}\n'
              \, '\]\@<!\n[=-]\{4,\}\n'
              \, lang, 'NonText')
      endfor
     
      call SyntaxRange#Include(
            \  '\c\[source\s*,\s*gherkin.*\]\s*\n[=-]\{4,\}\n'
            \, '\]\@<!\n[=-]\{4,\}\n'
            \, 'cucumber', 'NonText')
    endif
    endfunction
     
    call AsciidocEnableSyntaxRanges()

    The gherkin one, is there separately, since for the gherkin language, we're going to use the cucumber syntax file.

    Since the SyntaxRange registration it's in the syntax file, it will only activate when editing asciidoc files.

    Enjoy :)

    PS: I inspired for the SyntaxRange calls from dahu's vim-asciidoc, but I just rewrote the RegExp to better match the start of the source.

    PS2: For doing live html visualising of the file, you can use fast-live-reload:

    1
    2
    3
    4
    5
    6
    fast-live-reload test.adoc -e "asciidoctor test.adoc" -nn test.html
    1. Will notify the changes for clients on port 9001
    2. and will serve the content from test.adoc on port 9000
    3. and will monitor and execute when files change in subfolders:
       a: test.adoc -> asciidoctor test.adoc (no refresh)
       b: test.html    

    Then just open the http://localhost:9000/test.html in the browser and watch it change as you save.

    PS3: In the screenshot there is also vim-airline installed with the powerline fonts active.

    PS4: For Markdown you need another syntax file, and different regexps for matching code blocks.

  • Vimscript: Where "true" is False, and "false" is Still False.

    Found this gem while reading the documentation from good ol' vim:

       What Vim calls true is anything that is not zero.  Zero is false.
            Note:
            Vim automatically converts a string to a number when it is looking for
            a number.  When using a string that doesn't start with a digit the
            resulting number is zero.  Thus look out for this:
                    :if "true"
            The "true" will be interpreted as a zero, thus as false!

    First language that I know of, where checking references to stuff actually return false.

  • Why Apply Makes No Sense in UIs

    Do you remember that there was a time in Windows when all the UIs used to have the three magic buttons: 'Ok', 'Apply' and 'Cancel'?

    • Ok would apply the settings, and close the dialog,
    • Apply would apply the settings, and leave the dialog open and
    • Cancel would close the dialog.

    My brother used to tell me, man, it's easy to implement this, since 'Ok' becomes only:

    1
    2
    3
    4
        public void onOkClicked() {
        	this.onApplyClicked();
            this.onCancelClicked();
        }

    And here it is (almost) the same reminiscence in Eclipse (org.eclipse.jface.preference.PreferencePage).

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
        /**
         * Performs special processing when this page's Apply button has been pressed.
         * <p>
         * This is a framework hook method for sublcasses to do special things when
         * the Apply button has been pressed.
         * The default implementation of this framework method simply calls
         * <code>performOk</code> to simulate the pressing of the page's OK button.
         * </p>
         
         * @see #performOk
         */
        protected void performApply() {
            performOk();
        }

    Oh man, how times have changed... oh wait.

    PS. If you want to apply the changes, and keep the dialog open, because you want your users to be able to preview the changes, just make those buttons: 'Apply' and 'Close'.

  • Why I Love Bash

    Because in it I can alias things, for example:

    1
    2
    alias idle='PYTHONPATH=`pwd` idle'
    alias python='PYTHONPATH=`pwd` python'

    This allows me to run python in a folder of my choice and having it instantly available in my python path.

    Neat.

    This is so I can have python modules in a decent hierarchy.

Germanium

The one to rule them all. The browsers that is.

SharpKnight

SharpKnight is an Android chess game.

MagicGroup

MagicGroup is an eclipse plugin.