At RedBit, we have teams of people working on projects at one time. One of the key items to practice in any software development project is coding standards.

Now you can go all crazy with coding standards and you can write hundreds of pages of coding standards that developers on teams should follow, and believe me I’ve seen it! Problem with this is developers are more concerned with following these standards than solving real customer problems.

You can also just use the default ‘standards’ that Visual Studio or Visual Studio Code but sometimes developers change the default settings which causes some issues and primarily deal with developers having preferences such as ‘curly brace on same line or next line’ as follows


function(value)
{
  // do something
}

as opposed to


function(value){
  // do something
}

When developers have different settings in their IDEs consider the following scenario. If developer A implements the first function, then Developer B has goes in the same file and modifies a different part of the file and the IDE formats the file to their local workstation standards, then GIT will not only take the code changes, but will also take the formatting changes. These are really superficial changes in my opinion.

JavaScript and StandardJS

For the web applications we build at RedBit we use React and sometimes NodeJS so if you don’t have standards in place, things could get a bit messy. Some developers like spaces instead of tabs, curly braces on the first line like above but everyone has differences.

We have implemented StandardJS because it’s simple and allows the team to focus on developing code, not worrying about standards.

The following are the ‘The Rules’ in place out of the box

  • 2 spaces – for indentation
  • Single quotes for strings – except to avoid escaping
  • No unused variables – this one catches tons of bugs!
  • No semicolons – It’s fine. Really!
  • Never start a line with (, [, or `
  • This is the only gotcha with omitting semicolons – automatically checked for you!
  • Space after keywords if (condition) { … }
  • Space after function name function name (arg) { … }
  • Always use === instead of == – but obj == null is allowed to check null || undefined.
  • Always handle the node.js err function parameter
  • Always prefix browser globals with window – except document and navigator are okay
  • Prevents accidental use of poorly-named browser globals like open, length, event, and name.

This was taken directly from StandardJS website but make sure you read more for a complete list of all the rules.

Installing StandardJS

To get everything installed you need to have NodeJS installed which will give ‘npm’. There are two ways to install StandardJS. First is locally for your project and it’s as simple as running the following for saving in your local project


npm install standard –save-dev


Second is globally so you can run it from anywhere in the command line on your files.


npm install standard –global


Recommend still running the local one, so your ‘package.json’ gets updated to show StandardJS within ‘devDependencies’ section.

Updating package.json

When you do an ‘npm init’ to initialize a new ‘package.json’ you will get something similar to the following


{
  "name": "standardjs-testing",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Mark Arteaga",
  "license": "MIT"
}

Now you can change the ‘scripts’ section to something as follows


"scripts": {
  "test": "standard"
},

If you have a ‘start’ script you can do something along the lines of


"scripts": {
  "start": "standard && react-scripts start"
},

Let’s assume I had the following


const t = '';

class App extends Component {
  render () {
    return
      <div>my div</div>
    }
  }

ReactDOM.render(
  <App/>,
  document.getElementById('root')
)

StandardJS would give the following warning:


Compiled with warnings.

./src/index.js
  Line 22: 't' is assigned a value but never used no-unused-vars

Search for the keywords to learn more about each warning.
  To ignore, add // eslint-disable-next-line to the line before.

Developers Committing with Warnings

One thing that we try to avoid is committing code with active warnings in the code base. This is not always possible but we try to avoid as much as possible.

To circumvent this we do two things

Git Pre-commit Local Hooks

The StandardJS site has a perfect example on ‘pre-commit’ hook and you can find it here but here is the pre-commit hook for reference


#!/bin/bash

# Ensure all JavaScript files staged for commit pass standard code style
function xargs-r() {
# Portable version of "xargs -r". The -r flag is a GNU extension that
# prevents xargs from running if there are no input files.
#!/bin/bash 

# Ensure all JavaScript files staged for commit pass standard code style 
function xargs-r() {
  # Portable version of "xargs -r". The -r flag is a GNU extension that 
  # prevents xargs from running if there are no input files. 
  if IFS= read -r -d '' path; then
    { echo -n "$path"; echo -ne "\0"; cat; } | xargs $@
  fi
}
git diff -z --name-only --cached --relative | grep -z '\.jsx\?$' | xargs-r -0 -t standard
if [[ $? -ne 0 ]]; then
  echo 'JavaScript Standard Style errors were detected. Aborting commit.'
  exit 1
fi

If you don’t know what a ‘pre-commit’ hook is see Git Hooks on Atlassian site.

Automated Builds

We have a process where we go through a code review on every PR, but our PR process also attempts to build the code that is included in the PR and runs tests and runs StandardJS as part of the build process.

In our ‘package.json’ we usually have something as follows


"scripts": {
    "build": "standard && react-scripts build",
  }

which will run StandardJS when we build the React project.

Fixing the Code

The two above solutions tend to work fairly well except when someone removes their pre-commit hooks or never sets them up. The automated builds we have in VSTS are acting like a ‘gateway’ for our PR process before we even start reviewing code, so if the committed code does not comply with standards, the developer will get notified.

If StandardJS ever brings back a warning or an error you have two options. First is go to every line that has the error or warning and manually fix it. If you are new to JavaScript or still learning the standards, I recommend this.

Second options is to just run a simple command and that is


standard –fix


Standard will then go in and fix and spacing issues, tabbing issues etc.

Visual Studio Code and StandardJS

If you use Visual Studio Code, you have the ability to set StandardJS as your default formatter. I use JavaScript Standard Style and have set it up to automatically fix issues when I save a file so I don’t have to think about ‘space before a curly’ type issues. To set this up do the following

  1. In VSCode open the Extensions tab (CTRL-SHIFT-X)
  2. Search for ‘Javascript Standard Style’
  3. Install and then reload VS Code
  4. Click ‘File – Settings’
  5. In the user settings add “javascript.validate.enable”: false and “standard.autoFixOnSave”: true

Your settings should look something like the following


{
    "javascript.validate.enable": false,
    "standard.autoFixOnSave": true
}

Now whenever you save a file, it will make sure you are adhering to ‘standardjs’ standards and life is good!

Wrap Up

So as developers we all have our different styles of writing code, but when working with a team you should definitely look at putting some standards in place and making it as easy as possible for developers to follow those standards. This will allow developers to focus on solving customer problem and not worry so much about code formatting.

Leave a Reply