阅读笔记 - Clean Code JavaScript

57 阅读1分钟

Variables

  • Use meaningful and pronounceable variable names
  • Use the same vocabulary for the same type of variable
  • Use searchable names
  • Use explanatory variables
  • Avoid mental mapping, explicit is better than implicit
  • Don't add unneeded context, don't repeat your variable name
  • Use default arguments instead of short circuiting or conditionals

Functions

  • Function arguments (2 or fewer ideally), use destructuring syntax
  • Function should do one thing, the most important rule in software engineering
  • Function names should say what they do
  • Functions should only be one level of abstraction, split up functions leads to reusability and easier testing
  • Remove duplicate code, follow the SOLID and DRY principles
  • Set default objects with Object.assign, the same key will be overwritten by the target object
  • Don't use flags as function parameters
  • Avoid side effects
  • Don't write to global functions
  • Favor functional programming over imperative programming
  • Encapsulate conditionals
  • Avoid negative conditionals
  • Avoid conditionals
  • Avoid type-checking, otherwise use typescript
  • Don't over optimize
  • Remove dead code

Objects and Data Structures

  • Use getters and setters
  • Make objects have private members

Classes

  • Prefer ES6 classes over ES5 plain functions
  • Use method chaining
  • Prefer composition over inheritance

SOLID

  • Single Responsibility Principle (SRP)
  • Open/Closed Principle (OCP)
  • Liskov Substitution Principle (LSP)
  • Interface Segregation Principle (ISP)
  • Dependency Inversion Principle (DIP)

Testing

  • Single concept per test

Concurrency

  • Use Promises, not callbacks
  • Async/Await are even cleaner than Promises

Error Handling

  • Don't ignore caught errors
  • Don't ignore rejected promises

Format

  • Use consistent capitalization
  • Function callers and callees should be close

Comments

  • Only comment things that have business logic complexity
  • Don't leave commented out code in your codebase
  • Don't have journal comments
  • Avoid positional markers