“… He decided that Blub was enough, and his mind had been assimilated into Blub. “– Paul Graham, Hacker and Painter

preface

I don’t like shuttle-style if/else statements in business code, which are complex and bloated, and switch is much more elegant than if/else, at least aesthetically. If compared across languages, ReasonML’s pattern matching is far better than normal Switch statements. In this article, I will briefly introduce several alternatives to if/else. The only way to open our minds is to learn more about how to code, and if we don’t learn more about the possibilities of writing code, we may become controlled by code.

if/else

Let’s take an after-sale process as an example. After purchasing a product, users may contact the merchant for after-sales service due to reasons such as wrong parts, missing parts, quality problems, and inconsistent description, which may involve after-sales support services such as refund, return, replacement, and replacement. The after-sales service provided by the merchant will also affect the user’s preference for the merchant. In such a scenario, we assume the following pseudocode:

In this scenario, each kind of after-sales cause-oriented after-sales support service content is different. For example, users cannot choose to replace faulty parts. As a result, our criteria become a two-dimensional list of reasons * support services. At this time, plus according to the different after-sales reasons and after-sales support services, the judgment condition is no problem to rise to three-dimensional: [after-sales reasons * after-sales support services * user preferences]

Obviously, if/else statements are inadequate in this business-heavy area for the following reasons:

  1. Judge condition postpositionThat is to say, in} else if (serviceReason === 'quality problem ') {In a sentence, the criteria are usually found at the end of the line, and the content is not highlighted, so it is often confused with the next line of normal code.
  2. Indenting is not clear, and finding the end of an if statement is always a burden when reading code as the number of levels increases or as the content in curly braces lengthens.
  3. Luxury line breaks, when the logic in an if/else statement is short, likeelse { user.love(-5 }This code, taking up three lines of space, is too extravagant.

Ternary operator/short circuit expression

In some simple expressions, we can use the ternary operator or short-circuit expression to simplify the judgment. For example, the call to user. Love can be separated into a single sentence, so the following judgment can be simplified:

Comma operator

With parentheses and comma operators, we can turn statements into expressions to execute. Flexible use of the comma operator enables triadic or short-circuiting to support some more complex cases:

This code, however, is not recommended in the Standard specification. ESLint will warn you to convert this line to if/else. Of course, you can also modify the ESLint specification to turn warnings off, if you (and your team) like it that way, and don’t simplify for the sake of simplifying.

switch/case

When dealing with complex multi-branch judgments, most people use switch as an alternative to long if/else. How do you feel about this?

Unfortunately, the switch statement is not much better than if/else. The only thing I want to emphasize is that in the example above, almost all of the judgment keywords (such as switch, case, &&, which belong to the code highlighting area) are in the first two primitives at the beginning of each line. So for now, switch is better than if/else in terms of the sheer difficulty of finding judgment conditions, although this benefit wears off as the number of decision branches increases (which is a shame).

I also regret that the switch statement cannot be used with the short-circuit operator. Here is an example of an error:

Slightly uncomfortable, since using the if judgment increases indentation. Now let’s look at a more concise way of thinking about it.

Separate configuration data from service logic

There are no prerequisites for the separation of configuration data from business logic and, like the tri-mesh short-circuit expression, you can start using it in your code at any time. To use configuration logic separation, it is usually necessary to define an object to store data configuration and define a flag as the key of configuration. The value of configuration can be any type of value such as function or array. In the place where the logic is executed, the business logic method under the current judgment condition can be obtained only by comparing the judgment condition with flag:

Did you feel like you had a light in your eyes?Suggest that thumb up

In the code snippet above, we have separated the data configuration for each state from the code that executes the business logic, making the code much shorter. With the comma operator, we can simultaneously execute the business logic function and return the user’s image score of the store.

If you don’t want to be so radical, perhaps the following code is a good practice:

More flexible data configuration

In the previous section, we used objects for data configuration. If there is one regret, it is that although the value of the property can be of any type, the property itself can only be a string, which makes the separation of configuration logic difficult in certain scenarios. Imagine the following scenario: at the end of each month, the merchant will select the enthusiastic fans (with a liking level greater than or equal to 100) to send a message “Thank you” with a coupon of 10 yuan, ordinary fans (with a score of 0-100) to send a message “thank you “, black fans (with a score of less than 0) to send a message” sorry “with a coupon of 10 yuan.

Wait, the liking score is variable!

Obviously we can’t handle such data with objects (as long as I’m not crazy), as follows:

If /else? The bad news: Maybe.

However, I must emphasize that if the judgment conditions are complicated enough — for example, the merchants not only give coupons, but also send QQ red diamonds/green diamonds/yellow diamonds /… A gift of judgment — using if/else still leads to the same code mess we mentioned in the first section.

So the good news is that using configuration logic separation can handle more complex and messy scenarios (and you should). Do you remember the slight regret that the property itself can only be a string? Now we are going to solve this problem! Take a look at the following code:

Using Map for data configuration is a great way to write it, but if you must be compatible with Internet Explorer, you must consider using other data structures instead of Map:

The different code styles we mentioned in the two sections above all follow the idea of taking ‘configuration’ one step ahead of judgment. In real business, you can also try a mixture of configuration logic separation and conventional judgment conditional notation, where the main consideration should be whether to configure lead or judge lead configuration.

After the language

This article mainly introduces several alternatives to if/else in common scenarios, such as the tri + comma operator, using objects /Map/ even groups to separate configuration data from business logic. Although the idea of handling business logic is the same, the actual feeling of writing each method is different. Please look at the officer carefully taste some.

Finally, it would be nice if this article could give you some thoughts and thoughts on the code. If there are any incongracies in this article, please point them out in the comments.

The code performance

I haven’t actually looked at the performance costs of various writing methods, but if you’re interested, try 👍

To read more

  • A more elegant way to write complex JavaScript judgments
  • [Brief analysis] Replace if-else and switch schemes in specific scenarios
  • [Exploration] Maximize code reuse during development
  • MDN: Map