Tests and Code Quality - Linters Are Static, and That's Already Good
Now that you’re fired up about tests with part 1 of the series, let’s see how we can improve our code further upstream.
While writing code, we’re going to use a linter.
What is a linter? Historically, lint was the first syntax analysis tool, a UNIX command for the C language. Well yes, I use interpreted languages, whereas C is a compiled language. Compiling means turning your code into a language usable by machines that only understand 0s and 1s (the dummies).
Basic compilation goes like this: you head off for a twenty-minute coffee break, happy with your work and, boom, when you come back the compilation has failed miserably for some obscure reason.
With a linter, we get warned about some of the errors in our code before we run it.
Careful! It’s still static analysis. So mostly syntax errors and style issues.
In Javascript
For Javascript, the choice is easy: the standard is ESLint.
To set it up just the way we like it, we add an .eslintrc file at the root of the project and off we go!
{
"parser": "babel-eslint",
"extends": ["airbnb"],
"env": {
"es6": true,
"node": true,
"browser": true
},
"rules": {
"jsx-a11y/href-no-hash": "off",
"comma-dangle": 0,
"linebreak-style": 0,
"react/jsx-uses-react": 2,
"react/require-default-props": "off",
"react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }]
},
"plugins": ["react"]
}
Let’s break it down:
- parser: here babel-eslint, which lets ESLint understand ES6.
- extends: airbnb means we want to use the style rules provided by Airbnb
- env: specifies the environments we want to use for our project
- rules lets us give ESLint specific rules, for example to ignore the unused React import in jsx files.
- plugins: for a React project, obviously!
But since we don’t like rules, we can add exceptions in our files:
/* eslint-disable no-underscore-dangle */
/* eslint-disable no-unused-expressions */
/* eslint-disable no-undef */
In Python
For Python, we have more choice of linters.
Pylint and Flake8 are quite similar; they follow the PEP8 recommendations, except that Flake8 supports precommit hooks with Git and Mercurial.
And the new kid on the block, Black, is more than a linter: it’s a tool that reformats the code for you, with rules that differ from PEP8. For example, line length, historically 79 characters, is extended to 88 here.
The appeal of Black comes from its simplicity. No more debates about which code style to apply, no complicated settings: at worst you run Black in a precommit hook, and that’s it.
The post-match recap
A short article, but with links to dig deeper. Something to keep you busy until next week for part 3.