Refactoring is critical for every developer, especially for advanced programmers who need to advance. According to the 80/20 rule, 20% refactoring will solve 80% of the bad code. I recently to consult more js coding guidelines and to read the way of clean code, refactoring: improving the design of existing code, two classical books, it is strongly recommended that every once in a while to see, every time a new experience), sort out the following main points, to help everyone with the minimum of memory, most bad code refactoring. For a comprehensive overview of refactoring, see the AI Javascript style guide I’ve put together

Bad code judgment

Bad code varies from person to person and from project to project, but the following are the most likely examples of bad code that require refactoring.

  • Duplicate code
  • Too long to function
  • Too much class
  • Too long parameter list

refactoring

1. Good naming

Good naming runs through the whole software coding process, including the rational use of case definition, indentation and so on. There are a lot of lint or Format tools available for front-end engineering, which can be very convenient to help with engineering detection and automation. If you don’t know, you can check out the author’s FRONT end tool chain. Whether it’s a variable name, a function name, or a class name, a good name will speed up your development and your code reading, because your program will be read more often than it will be written. Read the excellent source code on Github, and sometimes just look at the function name to see what the author is trying to do.

// bad
var yyyymmdstr = moment().format('YYYY/MM/DD');

// good
var yearMonthDay = moment().format('YYYY/MM/DD');
Copy the code
// bad
function dateAdd(date, month) {
  // ...
}

let date = new Date(a); dateAdd(date,1) DateAdd (date, 1) Note: This is a simple example, but I hope to keep this in mind when doing projects

// good
function dateAddMonth(date, month) {
  // ...
}

let date = new Date(a); dateAddMonth(date,1);
Copy the code

2. Functions have a single responsibility

One of the most important principles in software engineering. This is a common problem for developers who have just graduated from school and feel that the business logic is too complex to subdivide into individual functions and write long business functions. However, according to the author’s guiding experience, most of them are too many temporary variables, leading to the inability to see the essence of business logic. In fact, by breaking down the responsibility step by step, breaking it down into smaller functions and naming them with appropriate names, you can quickly understand the nature of the business and perhaps even find hidden bugs.

// bad
function handle(arr) {
    // Array decrement
    let _arr=[],_arrIds=[];
    for(let i=0; i<arr.length; i++){if(_arrIds.indexOf(arr[i].id)===- 1){ _arrIds.push(arr[i].id); _arr.push(arr[i]); }}// Iterate over the substitution
    _arr.map(item= >{
        for(let key in item){
            if(item[key]===' '){
                item[key]=The '-'; }}});return _arr;
}

// good
function handle(arr) {
    let filterArr = filterRepeatById(arr)
    return replaceEachItem(filterArr)
}
Copy the code

3. Make the presentation clearer by introducing explanatory variables or functions

// bad
if (platform.toUpperCase().indexOf('MAC') > - 1 && browser.toUpperCase().indexOf('IE') > - 1 && wasInitialized() && resize > 0) {
  // do something
}

// good
let isMacOs = platform.toUpperCase().indexOf('MAC') > - 1
let isIEBrowser = browser.toUpperCase().indexOf('IE') > - 1
let isResize = resize > 0
if (isMacOs && isIEBrowser && wasInitialized() && isResize) {
  // do something
}
Copy the code
// bad
const cityStateRegex = /^(.+)[,\\s]+(.+?) \s*(\d{5})? $/;
saveCityState(ADDRESS.match(cityStateRegex)[1], ADDRESS.match(cityStateRegex)[2]);

// good
var cityStateRegex = /^(.+)[,\\s]+(.+?) \s*(\d{5})? $/;
var match = ADDRESS.match(cityStateRegex)
let [, city, state] = match
saveCityState(city, state);
Copy the code
// bad
if (date.before(SUMMER_START) || date.after(SUMMER_END)) {
  charge = quantity * _winterRate + _winterServiceCharge
} else {
  charge = quantity * _summerRate
}

// good
if (notSummer(date)) {
  charge = winterCharge(quantity)
} else {
  charge = summerCharge(quantity)
}
Copy the code

4. Less nesting, return early

// bad
let getPayAmount = (a)= > {
  let result
  if (_isDead) result = deadAmount()
  else {
    if (_isSeparated) result = separatedAmount()
    else {
      if (_isRetired) result = retiredAmount()
      else result = normalPayAmount()
    }
  }

  return result
}

// good
let payAmount = (a)= > {
  if (_isDead) return deadAmount()
  if (_isSeparated) return separatedAmount()
  if (_isRetired) return retiredAmount()
  return normalPayAmount()
}
Copy the code

5. Replace conditional expressions with HashMap

// bad
let getSpeed = type= > {
  switch (type) {
    case SPEED_TYPE.AIR:
    return getAirSpeed()
    case SPEED_TYPE.WATER:
    returngetWaterSpeed() ... }}// good
let speedMap = {
  [SPEED_TYPE.AIR]: getAirSpeed,
  [SPEED_TYPE.WATER]: getWaterSpeed
}
let getSpeed = type= > speedMap[type] && speedMap[type]()
Copy the code

other

Practicing the refactoring methods listed above will solve most of the bad code in your project, but there are many other refactoring methods that can make your code clean and easy to read.

  • Clear project directory structure
  • ES6 + syntactic sugar
    • arrow function
    • rest
    • Function default arguments
    • async/await
    • Let/const instead of var
    • Array Methods
  • Often use all const and all uppercase letters
  • Use appropriate function or variable names instead of comments
  • Good at using the js && and | |
  • Avoid ‘negative situation’ judgments
  • Try not to write global functions and variables
  • Using functional programming, ES6 Array supports well
  • Remove duplicate code
  • Remove commented code

Refer to the article

  • clean-code-javascript
  • JavaScript coding Style guide
  • Google JavaScript Style Guide
  • The AirBnb JavaScript Style Guide