Software Programming

Kunuk Nykjaer

Javascript clean code idea – avoid comments – make your code self documenting

leave a comment »


The book clean code book by
Robert C. Martins
has some great ideas about how to write clean code.

I thought about how to write cleaner Javascript code and would share some ideas on that topic.

The authors prefer self documenting code over writing descriptive comment about the function.

For example.

Instead of writing

// closes the responsive menu on menu item click
$('.navbar-collapse ul li a').click(function() {
   $('.navbar-toggle:visible').click();
});

// ** BEGIN setup articles layout and filtering
// init Isotope
var $container = $('.articles-container').isotope({
    itemSelector: '.article-item',
    layoutMode: 'masonry',
    masonry: {
        columnWidth: 320
    }
});
// bind filter link click
$('.article-filter').on('click', 'a.filter', function() {
    var filterValue = $(this).attr('data-filter');
    $container.isotope({
        filter: filterValue
    });
    return false;
});
// ** END setup articles layout and filtering

You could write

+function closesTheResponsiveMenuOnMenuItemClick() {

   $('.navbar-collapse ul li a').click(function() {
      $('.navbar-toggle:visible').click();
   });

}();

+function setupArticlesLayoutAndFiltering() {

    var $container;

    +function initIsotope() {

        $container = $('.articles-container').isotope({
            itemSelector: '.article-item',
            layoutMode: 'masonry',
            masonry: {
                columnWidth: 320
            }
        });

    }();

    +function bindFilterLinkClick() {

        $('.article-filter').on('click', 'a.filter', function() {
            var filterValue = $(this).attr('data-filter');
            $container.isotope({
                filter: filterValue
            });
            return false;
        });

    }();

}();

Advertisements

Written by kunuk Nykjaer

February 9, 2015 at 1:42 pm

Posted in Javascript

Tagged with

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: