preface

With the iteration of the project, there may be more and more branch judgments in the code. When the logic involved is complicated or the number of branches is too large to maintain, we need to consider, is there a way to make the code more elegant?

The body of the

Use enumerated

Here we simply define an enumeration that represents the state.

public enum Status {
    NEW(0),RUNNABLE(1),RUNNING(2),BLOCKED(3),DEAD(4);

    public int statusCode;

    Status(int statusCode){
        this.statusCode = statusCode; }}Copy the code

Then we can call it directly through enumeration when we use it.

int statusCode = Status.valueOf("NEW").statusCode;
Copy the code

An elegant solution to the following code assignment

if(param.equals("NEW")){
    statusCode = 0;
}else if(param.equals("RUNNABLE")){
    statusCode = 1; }...Copy the code

Use the Optional

In a project, there are always some non-empty judgments, probably most people still use the following

if(null == user){
    //action1
}else{
    //action2
}
Copy the code

This is where Optional comes in. It makes non-null validation more elegant and indirectly reduces if operations. For those of you who haven’t heard about Optional, please Google it.

Optional<User> userOptional = Optional.ofNullable(user);
userOptional.map(action1).orElse(action2);
Copy the code

The above code is equivalent to the first, with some new features to make the code more compact.

Table driven method

Table driven is a programming pattern that essentially queries information from tables instead of logical statements (if,case). Let’s take a look at a case. The days of the month are obtained by month (just as a case demonstration, the data of February is not precise). Common practice:

int getMonthDays(int month){
	switch(month){
		case 1:return 31;break;
		case 2:return 29;break;
		case 3:return 31;break;
		case 4:return 30;break;
		case 5:return 31;break;
		case 6:return 30;break;
		case 7:return 31;break;
		case 8:return 31;break;
		case 9:return 30;break;
		case 10:return 31;break;
		case 11:return 30;break;
		case 12:return 31;break;
		default:return 0; }}Copy the code

Table driven method of implementation

int monthDays[12] = {31.29.31.30.31.30.31.31.30.31.30.31};
int getMonthDays(int month){
	return monthDays[--month];
}
Copy the code

In this case, a table is just an array, and you can query the array directly to get the data you want. Similarly, a container like a Map can be used as a table in our programming concept.

Map<? , Function<? > action> actionsMap =new HashMap<>();

// The initial configuration corresponds to the action
actionsMap.put(value1, (someParams) -> { doAction1(someParams)});
actionsMap.put(value2, (someParams) -> { doAction2(someParams)});
actionsMap.put(value3, (someParams) -> { doAction3(someParams)});
 
// omit null judgment
actionsMap.get(param).apply(someParams);
Copy the code

With Java8 lambda expressions, we store what we need to do in a value, which is called by matching a key.

Prejudgment return

As mentioned in the previous article “Bad taste in Optimizing code”, the following statement


if(condition){
   //dost
}else{
   return ;
}
Copy the code

Instead of

if(! condition){return ;
}
//dost
Copy the code

Avoid unnecessary branches and make your code more concise.

Other methods

In addition to the methods mentioned above, we can also use some design patterns, such as policy mode and responsibility chain mode, to optimize a large number of if and case cases, the principle of which will be similar to table driven mode, you can do it yourself, for example, in the use of Netty, There may be scenarios that require a large number of different commands to execute the corresponding action.

ServerHandler.java

if(command.equals("login")){
    // Perform login
}else if(command.equals("chat")) {/ / chat
}else if(command.equals("broadcast")) {// Broadcast information}...Copy the code

How to deal with it? Here to sell a mystery, you can think about it, notes will write a few Netty implementation of IM articles, when the time will be introduced in detail.

conclusion

Finally, not all if/else,switch/case should be optimized. It is best to optimize when we find “pain points” or “smell bad code”, otherwise you may write an extensible code that never extends. All the optimizations are for better iteration projects and better service to the business. Not optimization for optimization’s sake.


Public account blog sync Github warehouse, interested friends can help give a Star oh, code word is not easy, thank you for your support.

Github.com/PeppaLittle…

Recommended reading

How to Improve Efficiency with Java Reflection? “How to Use Java Logging correctly” “How to Learn Synchronous/Asynchronous/Blocking/Non-blocking”

Follow the late Night programmer to share the driest stuff