If else is one of the most frequently used keywords when writing code, but sometimes too much if else can give us a headache, as in this pseudo-code:
Is it breaking down? Although it is pseudo-code and looks exaggerated, in reality, when we review other people’s code countless times, we will find a similar situation, so we will discuss in detail in this article, is there any way to avoid writing so much if else?
Here are 9 ways to get rid of the “annoying” if else.
1. The use of the return
We use return to get rid of the extra else, as follows.
Code before optimization:
if (str.equals("java") {// Business code!true;
} else {
return ;
}Copy the code
Optimized code:
if (str.equals("java")) {
return ;
}
return false;Copy the code
This makes it look a lot more comfortable. It’s only one line of code, but it’s the line of code that makes the difference between the real expert and the average person.
“Do not take good small and not for, do not take evil small and for it”, “a thousand li dike, collapse nest”, said the same truth.
2. Using the Map
Using the Map array, the relevant judgment information can be defined 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";
}Copy the code
Let’s define a Map array to store the relevant judgment information:
Map<Integer, String> typeMap = new HashMap<>();
typeMap.put(1, "name");
typeMap.put(2, "id");
typeMap.put(3, "mobile");Copy the code
The previous statement can be replaced with the following line:
type = typeMap.get(ty);Copy the code
3. Use ternary operators
Ternary operators are also called ternary expressions or ternary operators/expressions, but they all mean the same thing.
Code before optimization:
Integer score = 81;
if (score > 80) {
score = 100;
} else {
score = 60;
}Copy the code
Optimized code:
score = score > 80 ? 100:60;Copy the code
4. Merge conditional expressions
In the project, some logical judgments can be changed into more simple and understandable logical judgment codes by combing and summarizing, as shown below.
Code before optimization:
String city = "Xi 'an";
String area = "029";
String province = "Shaanxi";
if ("Xi 'an".equals(city)) {
return "xi'an";
}
if ("029".equals(area)) {
return "xi'an";
}
if ("Shaanxi".equals(province)){
return "xi'an";
}Copy the code
Optimized code:
if ("Xi 'an".equals(city) || "029".equals(area) || "Shaanxi".equals(province)){
return "xi'an";
}Copy the code
5. Use enumerations
A new type, enum, was introduced in JDK 1.5, and we can use it to do a lot of things, such as this one.
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;
}Copy the code
To optimize, we first define an enumeration:
public enum TypeEnum {
Name(1), Age(2), Address(3);
public Integer typeId;
TypeEnum(Integer typeId) {
this.typeId = typeId; }}Copy the code
The previous if else judgment can be replaced with the following line:
typeId = TypeEnum.valueOf("Name").typeId;Copy the code
6. Use the Optional
In JDK 9, we improved the Optional class by adding the ifPresentOrElse() method to eliminate if else judgments.
Code before optimization:
String str = "java";
if (str == null) {
System.out.println("Null");
} else {
System.out.println(str);
}Copy the code
Optimized code:
Optional<String> opt = Optional.of("java");
opt.ifPresentOrElse(v ->
System.out.println(v), () -> System.out.println("Null"));Copy the code
Tip: Be careful to run the version, which must be JDK 9+.
7. Sort out and optimize judgment logic
Similar to point 4, we can write more understandable code by analyzing the logic semantics of if else, such as the following nested decision optimization.
Code before optimization:
// Age > 18if(age > 18) {// Salary > 5000if(salary > 5000) {// Is it beautifulif (pretty == true) {
return true; }}}return false;Copy the code
Optimized code:
if (age < 18) {
return false;
}
if (salary < 5000) {
return false;
}
return pretty == true; Copy the code
We need to try to change the inclusions in the expressions to parallelism, so that the code is more readable and logical.
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 way to remove if else methods.
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;
}Copy the code
To use polymorphism, we first define an interface, declare a public return typeId method in the interface, and add three subclasses to implement the three subclasses respectively, 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() {
return3; }}Copy the code
Note: For the sake of simplicity, we have put the class and interface in one code block. In practice, we would have created one interface and three classes to store separately.
At this point, our previous if else judgment can be changed to something like this:
IType itype = (IType) Class.forName("com.example." + type).newInstance();
Integer typeId = itype.getType();Copy the code
One could argue that this makes the code more complex, a classic example of “killing a chicken without killing a cow”. Here the author just provides a kind of realization idea and provides some simple version of the code, in order to provide developers in the actual development, more than a kind of idea and choice, the specific use does not need to be determined according to the actual situation. Flexible, draw inferences from one another, is the development of superior mind.
9. Use the Switch selectively
Many people are confused about the use of switch and if else, but in cases where both work, use switch because switch performs better than if else in constant branch selection.
If else:
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;
}Copy the code
The 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;
}Copy the code
In Java 14 you can use the switch code block, which 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; }}Copy the code
conclusion
Practice makes perfect shortage in one, success depends on forethought destroyed by. Programming is both a craft and a pleasure, and harvard’s most popular happiness course, The Method for Happiness, states that “the only way to be happy and happy is to devote ourselves wholeheartedly to a task that we can accomplish with a little effort!” Yes, too easy things usually can not arouse our interest, and too difficult work will make us lose confidence, only those seemingly difficult things can be done with a little effort, will bring us great happiness.
I think programming is the same, the ordinary way everyone can write, but not everyone can write elegant code, and this article is to provide some ideas to write elegant code, I hope to help and inspire you.
The last word
Original is not easy, if you think this article is useful to you, please click on a “look”, this is the greatest support and respect for the author, thank you.
Reference & acknowledgements
https://www.tuicool.com/wx/2euqQvZ
http://www.blogjava.net/xzclog/archive/2006/10/16/75399.html
Original: Public account Java Chinese community