ciplogic.com
Live with grace. Write superb software.

bestpractices

  • 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.

  • 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.

  • Linux Automatic Updates

    I generally tend to have quite a bit of virtual machines running Linux. Some of them CentOS, some of them Ubuntu. Probably so do you. Some of them are started more often, some of them lay dormant quite a while, and then when you boot them up for whatever reason, e.g. to test the migration of your blog from apache to nginx, you need to apply whatever updates.

    Super annoying, I know.

    Thus, here's an easy tip. Just add a script in /etc/cron.daily to do the updates. e.g. /etc/cron.daily/update-my-system. For example I set:

    apt-get update -y && apt-get upgrade -y

    if it's Ubuntu/Debian, or

    yum update -y

    if it's CentOS/RHEL.

    I do this also on all the development machines that I have a graphical interface, so I don't get that supper annoying dialog asking me for the updates.

    You boot, it updates.

    It stays up, it updates on a daily basis.

    It's that simple. I know I wrote about it before. But it's important.

    Update for CentOS

    See here: http://blog.ciplogic.com/index.php/blog/104-linux-automatic-updates-on-centos

     

  • Linux Automatic Updates on CentOS

    Here's an update for the automatic updates, geared at CentOS/RHEL only.

    Dumitru Ciobârcianu tells us that there is a package for CentOS that already does that, named yum-cron. Thus instead of editing files inside the /etc/cron.daily, you can get away with:

    yum install yum-cron

    This in turn will create two cron jobs, one daily to do the updates, and one weekly, that will also do cleanup such as:

    # cat /etc/yum/yum-weekly.yum 
    clean packages
    clean expire-cache
    ts run
    exit

    Furthermore it allows configuration for checking packages, and what not. So definitely on CentOS go with yum-cron, since it's the better alternative.

    Thank you Dumitru!

    On Debian/Ubuntu there is also a package named cron-apt, but that one by default will do only the update of the package definitions (apt-get update -y) and not the actual upgrade of the system.

  • 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.

Germanium

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

SharpKnight

SharpKnight is an Android chess game.

MagicGroup

MagicGroup is an eclipse plugin.