This is the question and answer of zhihu, and I have put my answers here.


The principle of

First, one of the most important tuning principles: code tuning should be done daily, not once a month or two, when it’s too late. Plus, since optimization is done daily, you don’t need to over-optimize at one time, just keep taking baby steps.

Why is this important? Because a lot of programmers write code and say “let’s not optimize it now, I’ll optimize it when I’m not so busy” and then… There is no next.

Basically, “bad code” is the result of “optimize it when you’re not busy.”

Don’t give yourself excuses for bad code

If you could keep your programs healthy by optimizing a little bit of code every day, could you?

In my observation, 90% of programmers fail to do this. Every day, they find reasons in their minds to write bad code, or to ignore existing bad code:

  1. I’m only maintaining this project for a few months, so there’s no need to write good code, someone will take over anyway.
  2. This project is from someone else’s hands, the code is really bad, to blame the previous people, it is not my fault, I randomly add some code on the line, can use the line.
  3. This is a short-term project, so there’s no need to write good code
  4. This is a long term project, the code will be optimized next year, just for now

So you see, no matter how much I tell them about how to optimize code, they won’t use it, and that’s the problem.

Many programmers complain about bad code and never try to fix it. (Just as many programmers complain about the poor quality of the people taught in the training class, but don’t write the beginner’s tutorial themselves)

Once done, it gets better

If you don’t want to be one of those programmers, you just have one firm belief: as long as the code passes through my hands, the quality will be slightly better.

You’ll be able to write code in no time. You may be eager to hear the tips for getting code right, but I’m telling you, the tips don’t really matter. It’s the belief that counts.

Then there’s the technique.

Step 1: Don’t write bad code

Are you stupid? You asked “how to optimize code” and your answer was “Don’t write bad code”? !

Yes, the first step to good code is not to write bad code, which means you need to know what bad code is:

How to write unmaintainable code – cool shell

This tutorial is very good. It summarizes the bad code in the market. There are several kinds of bad code:

  1. Bad variable name
  2. Bad comments
  3. Bad design
  4. Don’t write tests (all code without unit tests is bad code, learn unit tests!)

Basically all the new guys write bad variable names, bad comments, and bad designs every day, and they don’t write unit tests.

And they don’t even know how bad their code is!

So the first step is to understand the truth: 80% of your code is bad.

You just need to make it less bad and it’s good code…

Again: the first step is crucial: figure out what bad code is.

Step 2: Avoid repetition

The Don’t Repeat Yourself principle. If you find two lines of code that repeat themselves several times, you should wrap the two lines into a function, place them in an appropriate place, and call the function.

Step 3: Table driver programming

If your code has a lot of if… else … Structure, you don’t know how to optimize, you should use table driven programming.

Before optimization:

howManyDays(year, month){
    if(month === 1 ||
        month === 3 ||
        month === 5 ||
        month === 7 ||
        month === 8 ||
        month === 10 ||
        month === 12
    ){
        return 31
    }else if(month === 2){
        return isLeapYear(year) ? 29 : 28
    }else{
        return 30
    }
}
Copy the code

After the optimization:

howManyDays(year, month){
    const table = {
        1: 31, 3: 31, 5: 31, 7: 31, 8: 31, 10: 31, 12:31,
        4: 30, 6:30, 9: 30, 11: 30,
        2: isLeapYear(year) ? 29 : 28
    }
    return table[month]
}
Copy the code

Before optimization:

function calculateGrade(score){
    if(score>=90){
        return 'A'
    }else if(score >= 80){
        return 'B'
    }else if(score >= 70){
        return 'C'
    }else if(score >= 60){
        return 'D'
    }else {
        return 'E'
    }
}
Copy the code

After the optimization:

function calculateGrade(score){
    const table = {
        100: 'A', 
        90: 'A',
        80: 'B',
        70: 'C',
        60: 'D',
        others: 'E'
    }
    return table[Math.floor(score/10)*10] || table['others']
}    
Copy the code

Step 4: Use routines

Design patterns are some programming routines, and Unix programming principles are some programming routines.

Learn all the tricks, and then choose the right ones when you run into problems.

For example, module communication generally uses event mode or command mode;

For example, decoupling usually uses the middle layer;

For example, the lifecycle generally supports hooks or facets;

For example, performance optimization is generally to add caching;

For example, the API design must be orthogonal;

For example, complex data systems generally use commands to query the separation of responsibilities;

Like space for time and time for space;

This is a pretty complicated piece, and you’ll be wrestling with it for a long time, and there’s no general solution. The only general solution is tradeoff.

Step 5: Optimize every day

As I said in class, “optimize every day” is refactoring. “Optimize every year” is rewriting.

Optimization is about “getting better”, not “writing well once”.

Once you let go of your code, your code will quickly become rotten and difficult to recover from.

By revisiting your entire system every time requirements change and fixing what’s wrong, without allowing “improvise now and optimize later”, your code stays healthy and robust.

Unfortunately, most people can’t. Even I let my code down when there are too many requirements.

The above content is involved in my “JS In Brief” course, and the course handout is here.