Use concept naming to simplify and clarify your Javascript conditions

Concept naming comes naturally to most people but is still rarely seen in Javascript despite the benefits. In this post I’ll illustrate how a simple technique can make your Javascript code significantly more readable.

 
The benefits of writing simple, clear and human-readable Javascript code are well known if not always well practiced.  The other day, while skimming the source of some of the rules bundled with ESLint, I was pleasantly surprised to see many of them made use of “concept naming” for conditions. This is a practice common in many other programming languages but not something I see being used in Javascript very often, despite the benefits.

Let me illustrate the technique with a simple code snippet:


if (charsToMatch[line.charAt(cursorPos.ch)]) {
    // do something
} else {
    // do something else
}

The condition on line 1 is trivial but even something this simple can make us stop and pause as we try to work out what the test is doing, and why. If you’re new to the code or just haven’t worked on it for a while a lot of valuable time can be wasted trying to get an overview of the application flow. Each time we hit a condition we have to pause and ask “what are we trying to achieve here?”.

We could, of course, add a comment immediately before the condition but comments can quickly become out-of-date, incomplete or just plain wrong. For that reason there has been a general trend over the last few years to minimize or reduce the number of comments in source code, or even to abandon them altogether.

When it comes to conditions, there is a simple and reliable way of making your code more understandable – give a name to the concept that is expressed in the condition. In our simple example the intent of the condition might be to determine if the character at the cursor position is one that we don’t want to allow a user to enter. This is determined by checking if it appears in an array – charsToMatch.
We can rewrite our snippet to illustrate this concept:

var charAtCursorIsNotAllowedInInput 
       = charsToMatch[line.charAt(cursorPos.ch)];

if (charAtCursorIsNotAllowedInInput) { 
    // do something 
} else { 
    // do something else 
}

If I were to glance at the snippet above for the first time, I still wouldn’t necessarily know the specifics of the conditional test but I would immediately be able to glean the intent of the condition. It now more closely reflects how we think – in concepts rather than conditional statements – and is much more readable.

Of course, as conditions increase in complexity the benefits will become more apparent:

var charAtCursorIsNotAllowedInInput 
       = (charsToMatch[line.charAt(cursorPos.ch)])
         || (cursorPos.ch >= 0 
         && charsToMatch[line.charAt(cursorPos.ch - 1)]);

if (charAtCursorIsNotAllowedInInput) { 
    // do something 
} else { 
    // do something else 
}

In this snippet the test is more complex but the concept is unchanged and what is trying to be achieved is instantly understandable.

Am I suggesting you should always name your conditions? No. There is, of course, a slight overhead in the “noise” introduced by the extra variable (which I consider a small price worth paying) but, just as you wouldn’t find it necessary to comment every condition, you wouldn’t necessarily want to assign a name to every one either. As always, common sense and consideration for those that will come after you goes a long way.

I hope you can see from these simple examples that, like the judicious use of clearly named variables, applying concept naming to your conditions can make your Javascript code significantly more readable and easier to maintain.

Use ‘eslint-annotated-reset’ to introduce linting to your legacy project

Introducing linting to a badly maintained legacy project can be a traumatic experience but the stress can be drastically reduced by careful use of ESLint and eslint-annotated-reset.

You’ve finally got agreement – you’re going to introduce linting of your Javascript code to your project, a project that’s desperately in need some TLC. Naturally, after careful evaluation, your linter of choice is ESLint, but when you run it against your code base you’re overwhelmed by the number of errors:

627 errors? When are you going to get time to fix those?
627 errors? When are you going to get time to fix those?

In the image above, taken from a real-life project that shall remain nameless to protect the guilty, we can see an all-too-common result of simply applying ESLint with the default settings; legacy code that generates hundreds, sometimes even thousands, of errors per file.

Of course, you want to resolve those problems. You want clean, consistent and maintainable Javascript. That’s why you’re introducing ESLint in the first place. But… you also want to meet your deadlines and they don’t necessarily allow for a massive refactoring of your code. Neither do you want to alienate your team, some of whom may already be hostile to linting and eager for opportunities to derail its introduction.

It was for exactly this situation that I created eslint-annotated-reset. This is simply an ESLint configuration file – .eslintrc – that you download from GitHub and drop into the root folder of your project. The next time you lint your code you’ll notice a drastic change; zero errors or warnings. The reason for this is simple, all of the linting rules have been turned off!

the easiest way to eat an elephant is one bite at a time

Why would you run ESLint will all of the rules turned off? eslint-annotated-reset is based on the principle that “the easiest way to eat an elephant is one bite at a time”. You may not have time to resolve 600 errors today but you might be able to resolve 6 or maybe even 60. After turning off all of the rules by dropping the .eslintrc file from eslint-annotated-reset into your project you can then selectively and methodically turn the rules back on, one at a time.

To turn a rule on, simply:

  • edit the .eslintrc
  • locate the rule you want to implement
  • change the setting from 0 (off) to 1 (throw a warning) or 2 (throw an error)

Let’s say we want to fix some of those 627 problems we saw earlier. Let’s start by making sure that all equality tests use “===” or “!==” rather than “==” and “!=”. That’s considered a best practice and can help prevent pernicious  bugs.

After opening .eslintrc  we locate the rule, in this case called “eqeqeq” (you can find these names in the console output from ESLint). There it is on line 63. We can confirm from the description that it’s the rule we want (that inline description is where the “annotated” in the name comes from).

"default-case": 0,     // require default case in switch statements
"dot-notation": 0,     // encourages use of dot notation whenever possible ***
"eqeqeq": 0,           // require the use of === and !== ***
"guard-for-in": 0,     // make sure for-in loops have an if statement
"no-alert": 0,         // disallow the use of alert, confirm, and prompt

A simple change to turn the rule on:

"default-case": 0,     // require default case in switch statements</pre>
"dot-notation": 0,     // encourages use of dot notation whenever possible ***
"eqeqeq": 2,           // require the use of === and !== ***
"guard-for-in": 0,     // make sure for-in loops have an if statement
"no-alert": 0,         // disallow the use of alert, confirm, and prompt

and we can rerun ESLint:

A much more manageable 26 errors
A much more manageable 26 errors

The eqeqeq rule is now the only one turned on and we have a much more manageable 26 errors. We can make and commit those changes and take a further bite of our elephant another day.

When you’re updating .eslintrc bear in mind that some rules take optional parameters in addition to the 0, 1 or 2. In eslint-annotated-reset these are indicated by three asterisks at the end of the description. You can find more details of the allowed options on the ESLint web site at:

http://eslint.org/docs/rules/rule-name-here

For example, the documentation for the ‘eqeqeq’ rule can be found at:

http://eslint.org/docs/rules/eqeqeq

Details of the eqeqeq rule from the ESLint website
Details of the eqeqeq rule from the ESLint website



The current (first) release of eslint-annotated-reset includes all rules included in version 0.20.0 of ESLint, released on 24th April, 2015. For convenience, the rules in .eslintrc are organised in the same way as they appear in the documentation pages of the ESLint website. As new rules are added to ESLint, eslint-annotated-reset will be updated to ensure they are always in sync.

ESLint allows you to choose which rules and stylistic conventions you want to apply to your Javascript code. With eslint-annotated-reset you can apply them at your own pace.


More:

‘onelineperfile’: a custom formatter for ESLint

‘onelineperfile’ is a new custom formatter for ESLint that, unsurprisingly, displays one line per file. Linting details are displayed whether the file passed linting or not.

 
If you use ESLint you probably already know that it comes with six formatters (a.k.a. reporters) that allow you to change the way that messages output by ESLint are reported.
Briefly, the six styles are:

Stylish (the default formatter)

eslint_stylish

Checkstyle

eslint-checkstyle

Compact

eslint_compact

JSLint-XML

eslint-jslint-xml

JUnit

eslint-junit

Tap

eslint-tap

Each of these are good for what they do but none of them are exactly what I need, which is output with:

  • One line for each file processed
  • Each line to indicate the status of the linting; success, error or warning
  • Each line to indicate the number of errors / warnings, if any
  • No error details to be displayed, I can check and fix that in the editor if needed
  • A summary line showing the total number of files processed, the number which passed linting and the number with warnings or errors

The reason for these requirements is to allow the output to be used in an audit trail, for example as the result of running a Git pre-receive hook; I should easily be able to check that a particular file was linted and it’s status.

Luckily, ESLint is very extensible so I created a new formatter — onelineperfile — which meets all of my criteria.

Here’s sample output:

eslint_onelineperfile

The easiest way to add it to your project is using NPM:


npm install --save-dev eslint-onelineperfile

You can then run it directly from the command line:


eslint --format node_modules/eslint-onelineperfile/onelineperfile.js <span class="keyword operator shell">*</span>.js

If you prefer to automate ESLint you can do so using Grunt ESLint:

  grunt.initConfig({
    eslint: {
      options: {
        format: require('eslint-onelineperfile')
      },
      target: ['*.js']
    }
});

grunt.loadNpmTasks('grunt-eslint');
grunt.registerTask('default', ['eslint']);



More:

Ensuring editing consistency with .editorconfig

 
Today I updated my recently created GitHub repo configs to include my .editorconfig file. EditorConfig is one of those incredibly simple ideas that I initially hesitated to install (“is that all it does?”) but now find invaluable. By defining a few properties in a file that you store in your repo, usually in the root, you can go some way to ensuring that everyone that works on your source uses the same basic whitespace settings; indent style, indent size, line terminator, and so on.

Nowadays, many (most?) editors allow for settings at both the user and project level, but often a project repo doesn’t include a settings file for the project or, if it does, it’s for an editor that you don’t use. If you work on multiple projects with differing conventions or even just in a team where everyone uses their own favourite editor, EditorConfig can ensure consistency of layout and less time wasted in reformatting.

EditorConfig consists of two parts; a simple configuration file, .editorconfig, and an editor/IDE plugin. Once you have selected and installed the plugin for your preferred editor (at the time of writing there were over twenty available) you can set your preferences and you’re ready to go. As it’s a simple text file it can be checked into your repo to ensure that everyone working on your project shares the same settings.

The config file allows eight properties to be set with seven of them allowing you to control the appearance of your code.

EditorConfig

EditorConfig is one of those things, like Markdown formatted ReadMe’s, that has become ubiquitous in open source projects. Even a cursory browse through GitHub or BitBucket will reveal that many projects make use of it.

My own .editorconfig can be found in my configs repo, a small collection of my most-used config files on GitHub.

More:

 

A new GitHub repo for config files

 
Earlier today I created a new public GitHub repo, called configs, appropriately enough. Simply put, this is going to be somewhere for me to keep my development configuration files so that they are always and easily accessible. Should anyone else find them of use then that would be a bonus.

The first config added to this new repo, .eslintrc, is for ESLint, the linting tool for Javascript and JSX that helps detect errors and highlights confusing constructs and violations of stylistic conventions. Having tried both JSLint and JSHint in the past I settled on ESLint as, compared to those alternatives, I find it to be more comprehensive in its checks, better documented and very easily extended.

I have a number of other config files I intend to add to the new repo but I’m taking the opportunity to give them the once over, refresh their contents and bring them up-to-date so updates will be spread over the next week or so.


More:

The four Brackets extensions I use most often

 
When it comes to writing code I have no interest in using a bloated IDE or some “I do everything, but none of it particularly well” editor. I work mostly with HTML, Javascript, Node.js and need a text editor that does that job and does it without getting in my way. If I need FTP, or SSH or one of the many other tools that are useful to developers then I’d rather use the inevitably superior standalone versions, not have them cluttering up and complicating the editor. That isn’t to say that there aren’t some non-editing functions that can benefit from being integrated with the editor, just that I’d rather choose what those features are.

Unfortunately, Sublime Text is limping ever closer to an early grave, Atom is no closer to being usable (unless you enjoy swimming in a half empty swimming pool filled with treacle). End result; I switched to using Brackets as my day-to-day editor. By now, Brackets is well enough known that there’s no point in me singing it’s praises. If you still haven’t tried it then you should. Unlike the competition, it’s free, open source, multi-platform, expandable, modern and has a very low learning curve.

The beauty of Brackets is that the editor itself is written using web technologies — HTML, CSS, Javascript. This also means that anyone who knows these technologies can extend the editor with extensions. In January 2015 (the last date I can find stats for) there were 616 extensions from 371 different authors. Of course, not all of these extensions are going to be useful but many are. In no particular order, here are four extensions that I use every day:

 

Brackets Git
by Martin Zagora

This extension is both incredibly powerful and easy to use. An instantly accessible dialog gives access to most of the Git functions you’ll need day-to-day; Pull, Push, Stage, Commit and many more. The interface is clean, intuitive and unobtrusive but if you find the built-in commands aren’t enough there is one click access to a Terminal/Command window opened in the projects folder.

All of the available commands can be accessed from here.
All of the available commands can be accessed from the bottom panel
Git Diffs of changes are displayed in an editor dialog
Git Diffs of changes are displayed in an editor dialog

A particularly useful feature is that changes made since the last commit are highlighted by a coloured block in the editor gutter. Clicking this block reveals the changes and gives us the option to revert it with just one click.

Changes made since the last commit can be viewed and reverted if necessary
Changes made since the last commit can be viewed and reverted if necessary

 

Brackets ESLint
by Andrée Hansson

ESLint is by far the most most configurable and most useful Javascript linter. Install this extension and your code can be validated for adherence to your coding standards and style guidelines on each save.

Code is linted on save
Code is linted on save

 

Show Whitespace
by Dennis Kehrig

Does what it says on the label.

Whitespace Off
Whitespace Off
Whitespace On
Whitespace On

 

White Space Sanitizer
by Miguel Castillo

If you’ve recently started using JSHint, JSLintESLint or some other, lesser-known, linting tool, the chances are (depending on the strictness of the settings) that you were shocked by the number of errors or warnings your code generated. Many of these alerts will likely be the result of your excessive or perverse use of whitespace. Lines with trailing spaces or containing only spaces, mixed tabs and spaces — all common mistakes. Install White Space Sanitizer and those problems will soon be a distant memory. On every save (but before linting) your white space will be cleaned up automatically.

 

All of these extensions and many, many more can be installed directly from within Brackets using the Extension Manager or from their respective GitHub repos.


More:

The work

 
This.

One could argue we should consider the good-enough-to-get-a-job skills to be the “baseline.” But there are a whole lot of front-end jobs to choose from, and getting one doesn’t establish much of a baseline. For me, I don’t want to get a job; I want to get invited to great jobs. I don’t want to go to work; I want to go to work with talented people. And I don’t want to be satisfied with knowing enough to do the work that needed to be done yesterday; I want to know how to do the work that will need to get done tomorrow.

— Rebecca Murphey



More: