O slideshow foi denunciado.
Utilizamos seu perfil e dados de atividades no LinkedIn para personalizar e exibir anúncios mais relevantes. Altere suas preferências de anúncios quando desejar.

Clean Code JavaScript

378 visualizações

Publicada em

Clean code best practice for JavaScript

Publicada em: Tecnologia
  • Seja o primeiro a comentar

  • Seja a primeira pessoa a gostar disto

Clean Code JavaScript

  1. 1. Clean Code JavaScriptReadable, reusable, and refactorable JavaScript code
  2. 2. @rizafahmi
  3. 3. Clean Code what is Best Practices some Tooling some
  4. 4. Clean Code what is
  5. 5. “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” 
 
 —Martin Fowler
  6. 6. How to measure code quality?
  7. 7. “Working code isn’t necessarily good code. Your code also needs to be easy to read, understand, and modify.” — Brandon Gregory
  8. 8. Clean Coderecap
  9. 9. Write code for human Quality means easy to read, understand, and modify
  10. 10. Best Practices some
  11. 11. “There are only two hard things in Computer Science: cache invalidation and naming things.” — Martin Fowler
  12. 12. Variables
  13. 13. Intention-revealing, searchable names
  14. 14. let d; let elapsed; const ages = arr.map(i => i.age);
  15. 15. let daysSinceModification; const agesOfUsers = users.map(user => user.age);
  16. 16. Meaningful distinctions and don't add extra, unnecessary nouns
  17. 17. let nameString; let theUsers;
  18. 18. let name; let users;
  19. 19. Easy to pronounce
  20. 20. let fName, lName; let cntr; let full = false; if (cnrt.size > 100) { full = true; }
  21. 21. let firstName, lastName; let counter; const MAX_CART_SIZE = 100; // ... const isFull = cart.size > MAX_CART_SIZE;
  22. 22. Functions
  23. 23. “Functions should do one thing. They should do it well. They should do it only.” — Robert C. Martin
  24. 24. function getUserRouteHandler (req, res) { const { userId } = req.params; // inline SQL query knex('user') .where({ id: userId }) .first() .then(user => res.json(user)); }
  25. 25. // User model (eg. models/user.js) const tableName = 'user'; const User = { getOne (userId) { return knex(tableName) .where({ id: userId }) .first(); } } // route handler (eg. server/routes/user/get.js) function getUserRouteHandler (req, res) { const { userId } = req.params; User.getOne(userId) .then(user => res.json(user)); }
  26. 26. Use long, descriptive names
  27. 27. /** * Invite a new user with its email address * @param {String} user email address !*/ function inv (user) { !/* implementation !*/ }
  28. 28. function inviteUser (emailAddress) { /* implementation */ }
  29. 29. Avoid long argument list
  30. 30. function createMenu(title, body, buttonText, cancellable) { // ... }
  31. 31. function createMenu({ title, body, buttonText, cancellable }) { // ... } createMenu({ title: 'Foo', body: 'Bar', buttonText: 'Baz', cancellable: true });
  32. 32. function createMenu({ title, body, buttonText, cancellable }) { // ... } createMenu({ body: 'Bar', title: ‘Foo', cancellable: true, buttonText: ‘Baz' });
  33. 33. Reduce side effect
  34. 34. let values = { a: 1 }; let b = 1; function impureFunction (items) { items.a = items.a * b + 2; return items.a; } let c = impureFunction(values); // `values.a` is 3, the impure function modifies it.
  35. 35. let values = { a: 1 }; function pureFunction (a) { let b = 1; a = a * b + 2; return a; } let c = pureFunction(values.a); // `values.a` has not been modified, it's still 1
  36. 36. Avoid callbacks
  37. 37. asyncFunc1((err, result1) => { asyncFunc2(result1, (err, result2) => { asyncFunc3(result2, (err, result3) => { console.lor(result3); }); }); });
  38. 38. asyncFuncPromise1() .then(asyncFuncPromise2) .then(asyncFuncPromise3) .then(result => console.log(result)) .catch(err => console.error(err));
  39. 39. const asyncFunc1 = async (err, result1) => { const result2 = await asyncFunc2(result1); const result3 = await asyncFunc3(result2); console.log(result3); }
  40. 40. Best Practicesrecap
  41. 41. Write meaningful, searchable names Functions should do one thing only Avoid callbacks, use async/await instead Reduce impure functions, use pure one
  42. 42. Tooling some
  43. 43. eslint
  44. 44. Tool that analyzes source code to flag programming errors, bugs, stylistic errors, and suspicious constructs.
  45. 45. $ npm install -D eslint $ ./node_modules/.bin/eslint --init
  46. 46. { "env": { "browser": true, "commonjs": true, "es6": true }, "extends": "eslint:recommended", "parserOptions": { "ecmaVersion": 2018, "sourceType": "module" }, "rules": { "indent": [ "error", 2 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ] } } .eslintrc.json
  47. 47. { "env": { "browser": true, "commonjs": true, "es6": true }, } .eslintrc.json
  48. 48. { "extends": "eslint:recommended", "parserOptions": { "ecmaVersion": 2018, "sourceType": "module" }, } .eslintrc.json
  49. 49. { "rules": { "indent": [ "error", 2 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ] } } .eslintrc.json
  50. 50. { "scripts": { "start": "parcel index.html", "test": "jest", "lint": "eslint src/*.js”, “lint:fix”: "eslint src/*.js —fix” } } package.json
  51. 51. $ npm run lint $ npm run lint:fix
  52. 52. prettier
  53. 53. Opinionated code formatter.
  54. 54. $ npm install -D prettier
  55. 55. { "printWidth": 80, "tabWidth": 2, "useTabs": false, "semi": true, "bracketSpacing": false, "trailingComma": “none" } .prettierrc.json
  56. 56. "scripts": { "start": "parcel index.html", "test": "jest", "lint": "eslint src/*.js”, “lint:fix”: "eslint src/*.js —fix”, "format": “prettier src/*.js —write" } package.json
  57. 57. $ npm run format
  58. 58. husky
  59. 59. Git hooks made easy. To prevent bad commit, push and more!
  60. 60. lint-staged
  61. 61. Run linters on git staged files.
  62. 62. $ npm install -D husky lint-staged
  63. 63. { "husky": { "hooks": { "pre-commit": "lint-staged" } }, "lint-staged": { "*.js": [ "npm run lint:fix", "npm run format", "git add" ] }, } package.json
  64. 64. $ git add . $ git commit
  65. 65. Toolingrecap
  66. 66. Use eslint for flag programming error Use prettier for consistent formatting Use husky and lint-staged for enforcing code quality
  67. 67. @rizafahmi @rizafahmi22

×