Please, don't ask me why I want to go if-else! because. . .

CSDN classmates, hello everyone, I am the second brother!

When I saw a high praise answer that was close to Wanzan, when I first saw it, the corners of my mouth were up, and I would laugh out of pigs, and then my mood went down sharply, inexplicably sad! The title is this:

Let’s take a look at the anonymous author’s answer first. Those who haven’t read it, remember to wash their faces with tears.

I once took over a piece of code and encountered a module with more than 30 if-else nested if-else modules.

I cursed in my heart, "Who wrote this stuff!" Then I went through the history of the code.

The general situation is like this: when the first programmer wrote this code, there were only 2 if-else; later, the demand gradually increased, first one or two, and then the quantitative change caused the qualitative change, so the logic branch expanded rapidly.

By this time, no one is willing to refactor the switch or design pattern. After all, the complexity is there, and if it collapses, it has to be backed up.

After about three or four programmers took over this code, they started programming in my current situation.

The first programmer never expected that such a simple logic would become so complicated in the future, and even when adding the first and second if-else, it was just added randomly.

So I think this pot is definitely Party A's, let his mother change his needs as he pleases. It feels better to think about it this way. Programming, the most important thing is to be open-minded!

So I added two if-else, then test, submit, and get off work.

In addition, if you really want to refactor the code, I suggest you first look at Xiao Fu’s "Relearn Java Design Patterns". Design patterns are typical solutions to common problems in software design. They are like pre-made blueprints that can be adjusted according to needs. , Can be used to solve the recurring design problems in the code. If you don't understand the design patterns, you can only catch them when you encounter these problems.

Design mode, awesome!

After reading the author's answer, the second brother endured the nameless sadness and said something.

In the programming career of more than ten years, I have indeed had countless impulses. I wanted to refactor and tune the original code. In the end, most of them died without disease, especially as I grew older, they became more and more courageous. I'm scared of things, some really don't dare to move, and can only reluctantly make the original code worse.

After all, backing up is a big deal, hehe.

Sometimes, code cannot be regarded as a work of art. It is important to be able to tolerate imperfections appropriately, the program can run, the number of bugs can be controlled, and what problems can be solved are also very important.

If refactoring occurs and something goes wrong, it is destined to take the blame, and it may also affect the test lady.

I remember that in the second year of working in a foreign company, because there was a newcomer in the group whose code was really bad, I couldn’t help but optimize it all over again. After all, as a Team Leader, I must be responsible to the newcomer and the team. What do you guys guess?

I was scolded by the leader!

The reason is very simple. We have introduced a bug. It has not been checked out during Code Review, and the test has not been tested. The result is in the formal environment. It happened that the leader was on a business trip in Japan, and the leader had to show the results to the leader. As a result, there was a bug in the program, and the leader was severely scolded.

The leader was approved, so naturally, an overseas phone call came over, and I was directly scolded and crying!

I was still young, so it was a grievance. But what can I do, who can do it if I can’t carry it?

Later when I returned to Luoyang, the team became smaller and my desire to rebuild came to my heart. After all, no one could control me this time. I just saw someone’s code rotten, I just had a violent operation and refactored to my satisfaction. until.

Even if a new bug is introduced, it doesn't matter, after all, the boss doesn't understand it, so foolish, hehe.

Although the boss doesn’t understand the code, he knows how to write code without bugs. After my unremitting efforts, I succeeded in instilling this idea into the boss. If there are no bugs, I increase the manpower of the test team. The leader is not willing to pay an extra salary. .

After the successful brainwashing of my boss, I really drifted to the extreme for a while, and even refactored my own code. Over and over again, the two most frequently read books on hand, one "The Way to Clean Code", one The "Refactoring and Improving the Design of Existing Code".

From simple variable naming, method naming, to reducing the number of lines of the method, you can split it as soon as possible, and try to ensure that the number of lines of each method does not exceed the length of a little finger. In order to adapt to the design pattern, I also bought a copy of "The Zen of Design Patterns", which was really exhausting.

Thinking about those days, it was crazy. Sometimes I really spent a lot of nights trying to fix the new bugs that I brought after refactoring.

But there is one thing to say, the progress of that period is also visible to the naked eye.

However, then again, for projects with high stability requirements, if the ability is not up to that point, try to refactor as little as possible. Maybe there will be a note in the version update log: XXX programmer is sacrificed to heaven Up!

It is best to wait until the leader can't help but give the order to die, and within a few days of waiting, be sure to move this shit mountain away! At that time, it won't be too late to flex your muscles.

If it is really unbearable, and the refactoring and tuning ideas cannot be used, I recommend a good way to everyone, which is to develop a hands-on project by yourself, which can be developed by yourself or mature on GitHub. For projects, such as vhr, mall, miaosha, etc. that I have always recommended, fork and pull down the source code, run a local run, try to read the source code, and if you think it needs to be refactored, just try it out. Something went wrong, and no one can affect it, right?

If some students feel that they are more powerful, they can experiment with the top third-party libraries. After refactoring, you must remember to test and attach your own test report when submitting the PR. If the author of the project thinks you are important If you have a high level of structure, you may become the maintainer of the project in a short time, and the resume is also a bonus item.

But for the pile of shit mountains in the company, try to be awkward when using the knife to avoid burying yourself.

Let's return to the topic of if-else and switch. Friends @yes mentioned ChannelEventRunnable class Dubbo source in the answer in the run()way I looked at Dubbo on GitHub source code with Sourcegraph plug-learning really is quite valuable.

public void run() {
    if (state == ChannelState.RECEIVED) {
        try {
            handler.received(channel, message);
        } catch (Exception e) { }
    } else {
        switch (state) {
            case CONNECTED:
                try {
                } catch (Exception e) {}
            case DISCONNECTED:
                try {
                } catch (Exception e) {}
            case SENT:
                try {
                    handler.sent(channel, message);
                } catch (Exception e) { }
            case CAUGHT:
                try {
                    handler.caught(channel, exception);
                } catch (Exception e) { }

Do you see it? In this code, first use if to make judgments, and then use switch to make branch judgments in else. Why not use switch all?

The official also gave a special explanation.

I have excerpted one of the key points, and everyone will understand it by looking at it.

Modern CPUs support branch prediction and instruction pipeline. The combination of these two can greatly improve CPU efficiency. For simple if jumps, the CPU can do branch prediction better. But for the switch jump, the CPU does not have many ways. The switch essentially takes the address from the address array and then jumps based on the index.

So, not in all cases, restructuring if-else into a switch is the best choice, but you still have to adapt to local conditions, so please, don't ask me why if-else is going all over the world!