Clean Code

  Alexey Ulianov Optimax Ltd

Front-end Tech Lead at Optimax Ltd
 

 Part 1. The problem

1. Possible errors

2. Code review

 Part 2. Decision

eslint

> 9000 stars

Who use

and other company

Philosophy

  • Everything is pluggable

  • Every rule Is standalone

  • ESLint does not promote any particular coding style

  • Is as transparent as possible

['1','2','3'].map(parseInt)
['1','2','3'].map(parseInt)

[1, NaN, NaN]

['1','2','3'].map(parseInt)

[1, NaN, NaN]

parseInt('1', 0);
parseInt('2', 1);
parseInt('3', 2); 

5 basic rules

  1. Possible Errors
  2. Best Practices
  3. Variables
  4. Stylistic Issues
  5. ECMAScript 6

> 300 rules

1. Possible Errors

These rules relate to possible syntax or logic errors in JavaScript code

Do not use the '===' operator to compare against -0.

no-compare-neg-zero

if (x === -0) {
    // doSomething();
}

2. Best Practices

These rules relate to better ways of doing things to help you avoid problems

Function 'a' has a complexity of 3.

complexity

/*eslint complexity: ["error", 2]*/

function a(x) {
    if (true) {
        return x;
    } else if (false) {
        return x+1;
    } else {
        return 4; // 3rd path
    }
}

3. Variables

These rules relate to variable declarations

  1. 'some_unused_var' is defined but never used.
  2. Read-only global 'some_unused_var'
    should not be modified.

no-unused-vars

/*eslint no-unused-vars: "error"*/
/*global some_unused_var*/

some_unused_var = 42;

4. Stylistic Issues

These rules relate to style guidelines, and are therefore quite subjective

no-mixed-spaces-and-tabs

/*eslint no-mixed-spaces-and-tabs: "error"*/


function main() {
// --->var x = 5,
// --->....y = 7;
    var x = 5,
        y = 7;
}

Mixed spaces and tabs.

5. ECMAScript 6

These rules relate to ES6, also known as ES2015

no-const-assign

/*eslint no-const-assign: "error"*/
/*eslint-env es6*/

const a = 0;
a = 1;

'a' is constant.

And more...

stylelint

> 4000 stars

stylelint can parse any the following non-standard syntaxes

by default: SCSS, Less and SugarSS

> 160 rules

who use

and other company

Part 3. Install

Install

npm install --save-dev eslint stylelint

yarn add eslint stylelint --dev

Config

.stylelintrc

.eslintrc

{
  "rules": {
    "no-console": "error"
  }
}

Run

"scripts": {

          "eslint": "npm run eslint",

          "stylelint": "npm run stylelint"

}

One more thing...

yarn eslint --fix src/**/*.js

yarn stylelint --fix src/**/*.css

Result

  • eslint + stylelint =
  • make code review
  • write unit test
  • use static type checker

Alexey Ulianov

Clean code

By Alexey Ulianov

Clean code

  • 463