Home Programming 9 Tips to Make Your if-else Look More Elegant

9 Tips to Make Your if-else Look More Elegant

195
0
9 Tips to Make Your if-else Look More Elegant
9 Tips to Make Your if-else Look More Elegant

if-else is one of the most frequently used keywords when we write code, but sometimes too much if-else will make us feel brain pain.

Is it very cruel? Although he is pseudo-code and looks exaggerated, in reality, when we review other people ’s code countless times, we will find similar scenarios, then we will talk in detail in this article, is there any way we can avoid Let’s write so many if-else?

This article provides 9 methods to solve those annoying if-else, let’s take a look.

1. Use return

We use to return remove the extra else, the implementation code is as follows.

Code before optimization:

if (str.equals("java")) {
    // Code of ! true;
} else {
    return ;
}

Optimized code:

if (str.equals("java")) {
    return ;
}
return false;

This looks a lot more comfortable. Although the difference is only one line of code, the gap between the real master and the ordinary person is reflected in this line of code.

“Don’t do nothing with goodness and smallness, and don’t do evilness with smallness .”

2. Use Map

Use the Map array to define related judgment information as element information to directly avoid if-else judgment. The implementation code is as follows.

Code before optimization:

if (t == 1) {
    type = "name";
} else if (t == 2) {
    type = "id";
} else if (t == 3) {
    type = "mobile";
}

We first define a Map array to store relevant judgment information:

Map<Integer, String> typeMap = new HashMap<>();
typeMap.put(1, "name");
typeMap.put(2, "id");
typeMap.put(3, "mobile");

The previous judgment statement can be replaced with the following line of code:

type = typeMap.get(ty);

3. Use the ternary operator

The ternary operator is also called the ternary expression or the ternary operator/expression, but it represents the same meaning.

Code before optimization:

Integer score = 81;
if (score > 80) {
    score = 100;
} else {
    score = 60;
}

Optimized code:

score = score > 80 ? 100 : 60;

4. Merge conditional expressions

Some logical judgments in the project can be changed to simpler and easier-to-understand logical judgment codes through combing and induction, as shown below.

Code before optimization:

String city = "Snook";
String area = "77878";
String state = "TX";
if ("Snook".equals(city)) {
    return "Snook";
}
if ("77878".equals(area)) {
    return "Snook";
}
if ("Snook".equals(state)){
    return "TX";

Optimized Code

if ("Snook".equals(city) || "77878".equals(area) || "TX".equals(province)){
    return "TX";
}

5. Use enumeration

JDK 1.5 introduced a new type-enum (enum), we can use it to complete many functions, such as the following.

Code before optimization:

Integer typeId = 0;
String type = "Name";
if ("Name".equals(type)) {
    typeId = 1;
} else if ("Age".equals(type)) {
    typeId = 2;
} else if ("Address".equals(type)) {
    typeId = 3;
}

When optimizing, we first define an enumeration:

public enum TypeEnum {
    Name(1), Age(2), Address(3);
    public Integer typeId;
    TypeEnum(Integer typeId) {
        this.typeId = typeId;
    }
}

The previous if else judgment can be replaced by the following line of code:

typeId = TypeEnum.valueOf("Name").typeId;

6. Use Optional

The Optional class was introduced from JDK 1.8. The Optional class was improved in JDK 9 and the ifPresentOrElse () method was added. We can use it to eliminate the judgment of if else.

Code before optimization:

String str = "java";
if (str == null) {
    System.out.println("Null");
} else {
    System.out.println(str);
}

Optimized code:

Optional opt = Optional.of("java");
opt.ifPresentOrElse(v -> 
 System.out.println(v), () -> System.out.println("Null"));

Tips: Pay attention to the running version, it must be JDK 9+.

7. Sort out optimization logic

Similar to the fourth point, we can analyze the logical judgment semantics of if else to write more understandable code, such as the following optimization of nested judgment.

Code before optimization:

// Older than 18
if (age > 18) {
    // Salary greater than 5000
    if (salary > 5000) {
        // Is its Enough?
        if (pretty == true) {
            return true;
        }
    }
}
return false;

Optimized code:

if (age < 18) {
    return false;
}
if (salary < 5000) {
    return false;
}
return pretty == true;

We need to try to change the inclusion relationship in the expression to a parallel relationship so that the code is more readable and the logic is clearer.

8. Use Polymorphism

Inheritance, encapsulation, and polymorphism are important ideas of OOP (object-oriented programming). In this article, we use the idea of ​​polymorphism to provide a method of removing if else.

Code before optimization:

Integer typeId = 0;
String type = "Name";
if ("Name".equals(type)) {
    typeId = 1;
} else if ("Age".equals(type)) {
    typeId = 2;
} else if ("Address".equals(type)) {
    typeId = 3;
}

Using polymorphism, we first define an interface, declare a public return typeId method in the interface, add three subclasses to implement these three subclasses, and the implementation code is as follows:

public interface IType {
    public Integer getType();
}
 
public class Name implements IType {
    @Override
    public Integer getType() {
        return 1;
    }
}
 
public class Age implements IType {
    @Override
    public Integer getType() {
        return 2;
    }
}
 
public class Address implements IType {
    @Override
    public Integer getType() {
        return 3;
    }
}

Note: For the sake of simplicity, we have put the classes and interfaces into a code block. In actual development, we should create an interface and store three classes separately.

At this point, our previous if else judgment can be changed to the following code:

IType itype = (IType) Class.forName("com.example." + type).newInstance();
Integer typeId = itype.getType();

Some people may say that this makes the code more complicated. This is a typical example of “killing the chicken with a slaughter knife”. The author here only provides an implementation idea and provides some simple versions of the code for developers to develop an additional idea and choice in actual development. The specific use does not need to be determined according to the actual situation. Flexibility and inferences are the best way to develop.

9. Selective use of switch

Many people don’t understand the usage scenarios of switch and if else, but in the case where both can be used, you can use switch as much as possible, because the switch’s performance will be higher than if else when selecting a constant branch.

if else judgment code:

if (cmd.equals("add")) {
    result = n1 + n2;
} else if (cmd.equals("subtract")) {
    result = n1 - n2;
} else if (cmd.equals("multiply")) {
    result = n1 * n2;
} else if (cmd.equals("divide")) {
    result = n1 / n2;
} else if (cmd.equals("modulo")) {
    result = n1 % n2;
}

switch code:

switch (cmd) {
    case "add":
        result = n1 + n2;
        break;
    case "subtract":
        result = n1 - n2;
        break;
    case "multiply":
        result = n1 * n2;
        break;
    case "divide":
        result = n1 / n2;
        break;
    case "modulo":
        result = n1 % n2;
        break;
}

The switch code block can be used in Java 14, and the implementation code is as follows:

// java 14
switch (cmd) {
    case "add" -> {
        result = n1 + n2;
    }
    case "subtract" -> {
        result = n1 - n2;
    }
    case "multiply" -> {
        result = n1 * n2;
    }
    case "divide" -> {
        result = n1 / n2;
    }
    case "modulo" -> {
        result = n1 % n2;
    }
}

Summary

Karma is good at diligence and frivolity, attains imagination and ruins. Programming is a craft, but it is also a kind of fun. Harvard ’s most popular happiness class, “The Method of Happiness”, reads, “The method that allows us to feel joy and happiness is nothing more than to devote ourselves to a little hard work. Work that can be done in one go! “Yes, things that are too simple usually cannot arouse our interest, and work that is too difficult can make us lose confidence, and only those that seem difficult but can be done with a little effort Things will bring us great happiness.

I think the same is true for programming. Everyone can write common methods, but not everyone can write elegant code. This article just provides some ideas for writing elegant code. I hope it can help and inspire you.

Previous articleIP Address, Subnet Mask, Default Gateway
Next articleHow To ByPass Google Drive Download Limit of 750GB

LEAVE A REPLY

Please enter your comment!
Please enter your name here