“This is the fifth day of my participation in the First Challenge 2022. For details: First Challenge 2022”

The body is translated from your-javascripts -smells


Open the IDE and look for code that “stinks”, like opening a refrigerator, finding smelly food and cleaning it out. Although there is a “peculiar smell” code, do not deal with, perhaps not so important, but this “peculiar smell”, is “erosion”, and then affect the whole refrigerator food warning.

The code:

let a = "start";
let b;

for(let i = 0; i < 5; i++) {
  b += a[i].toUpperCase();
}
Copy the code

Does it smell a little bit? Capitalize each letter and continue it with another value, regardless of the whole thing, and even worse, the number 5 of the loop is written dead, so there is nothing extensible about it.

First, treat this “peculiar smell” a bit:

let a = "start";
let b;

for(let i = 0; i < a.length; i++) {
  b += a[i].toUpperCase()
}
Copy the code

Then try to leave out the intermediate value and encapsulate a general method with a function;

let a='start'
let upperCaseStrFn=(str)=>{
    return str.split("").map(i=>i.toUpperCase()).join("")
}
console.log(upperCaseStrFn(a)) // START
Copy the code

In this way, the odor is eliminated.

If you look at upperCaseStrFn, you don’t need to know its internal implementation to know that this function is a way to capitalize every letter of a string, and that’s readability; At the same time, this function can not only handle variable A, it can also handle other variables that become, or extend within the function itself, which is extensibility;

Another problem with readability:

Let total_cost = order.getCost() * 1.52;Copy the code

See this line of code, oh, it is used to calculate the total, the cost of the order, times 1.52… Wrong! What is this 1.52?

Solve the odor:

Const MADRID_TAX_RATE = 1.52; let total_cost = order.getCost() * MADRID_TAX_RATE;Copy the code

Whoa, whoa, that 1.52 is the MADRID tax rate.

Separate data declaration and data processing, that is, low coupling, high cohesion code, easy to modify, change one, multiple effect;

Still have?

The single responsibility principle can effectively eliminate “odors”.

The more detailed and compact the pieces are, the more flexible they can be combined. Each block has a single function.

function saveUser(name: string, address: string, birthdate: Date, phone_number: string) { //... let diff_ms = Date.now() - birthdate.getTime(); let age_dt = new Date(diff_ms); let age: number = Math.abs(age_dt.getUTCFullYear() - 1970); / / /... }Copy the code

After the optimization:

function saveUser(usr: User) { //... let age: number = usr.getAge(); / /... }Copy the code

Not all of the optimized code is shown, but the key parts are easier to read, right? You don’t need to know exactly what getAge() does, just what it does. Because your eyes are focused on the saveUser() method.

Also, it’s common to encounter code like this:

function configureChristmasTreeLights(tree, mode) { switch(mode) { 'rgb_blinking': tree.setColors('rgb', { 'blinking': true, 'frequency': 10 }) break; 'rgb_fixed': tree.setColors('rgb', { 'blinking': false }) break; 'white_smooth': tree.setColor('white', { 'blinking': true, 'frequency': 1 }) break; default: throw new Error("Unrecognized mode used") break; }}Copy the code

The switch function is too big, and could get even bigger. So, to eliminate this “smell” :

/// Helper functions
function blinkingRGBLights(tree) {
  tree.setColor('rgb', {
    'blinking': true,
    'frequency': 10
  })
}

function fixedRGBLights(tree){
  tree.setColor('rgb', { 'blinking': false})
}

function whiteSmoothLights(tree) {
  tree.setColor('white', {
    'blinking': true,
    'frequency': 1
  })
}

//The actual function
function configureChristmasTreeLights(tree, mode) {
  const mapping = {
    'rgb_blinking': blinkingRGBLights,
    'rgb_fixed': fixedRGBLights,
    'white_smooth': whiteSmoothLights
  }
  
  try {
    mapping[mode](tree);
  } catch (e) {
    throw new Error("Unrecognized mode used")
  }
}
Copy the code

Map can be used to deal with multiple judgment conditions. Bengua knows this point well:

if(x===a){
   res=A
}else if(x===b){
   res=B
}else if(x===c){
   res=C
}else if(x===d){
    //...
}
Copy the code

To:

let mapRes={
    a:A,
    b:B,
    c:C,
    //...
}
res=mapRes[x]
Copy the code

There are:

Repetitive code encapsulates abstractions that help your colleagues, help them use your approach, and is a “good deed,” essentially creating wheels within a small area of the team for the benefit of everyone.

Little sense:

It’s really important to separate data declaration from data processing.

Let’s get rid of JavaScript odors

I’m Nuggets Anthony, output exposure input, technical insight into life, goodbye ~