Write an if without else to improve code readability

If-Else is usually a bad choice, it leads to complex design, poor code readability, and may lead to difficulties in refactoring.

1. Completely unnecessary Else block

This is perhaps one of the most guilty of those junior developers. The following example is a good illustration of what happens when you are considered great if-Else.
Insert picture description here
Simply remove the else block to simplify this process.
Insert picture description here

2. Value distribution

If you want to assign new values ​​to variables based on some input provided, stop the If-Else nonsense-a more readable method.
Insert picture description here
Although simple, it is terrible. First of all, If-Else is easily replaced by a switch here. However, we can simplify this code further by removing else completely.
Insert picture description here
If you don't use else, we will be left with clean, readable code. Please note that I also changed the style to a quick return instead of a single return statement-if the correct value has been found, there is no point in continuing to test a value

3. Prerequisite check

Generally, I find that if a method provides an invalid value, it doesn't make sense to continue execution. Assuming that we have the DefineGender method before, the required input value must always be 0 or 1.
Insert picture description here
There is no point in executing this method without value verification. Therefore, before allowing the method to continue, we need to check some prerequisites.

Applying protection clause defensive coding techniques, you will check the input value of the method, and then continue to execute the method.
Insert picture description here
At this point, we have ensured that the main logic is only executed when the value falls within the expected range.
Now, IF has also been replaced by ternary, because it is no longer necessary to return "unknown" by default at the end.

4. Convert If-Else to a dictionary-completely avoid If-Else

Suppose you need to perform some operations, which will be selected based on certain conditions, and we know that more operations must be added in the future.
Insert picture description here
Maybe someone prefers to use the tried and tested If-Else. If you add a new operation, you can simply add other content. Very simple. However, this method is not a good design in terms of maintenance.

Knowing that we need to add new operations in the future, we can reconstruct the If-Else into a dictionary.
Insert picture description here
The readability has been greatly improved, and the code can be inferred more easily.

Note that the dictionary is placed inside the method for illustration purposes only. You may wish to provide it from elsewhere.

Guess you like

Origin blog.csdn.net/QiuHaoqian/article/details/110919636