Skip to content

Instantly share code, notes, and snippets.

@penglongli
Created February 20, 2017 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save penglongli/a28e85520eb1827932d356dcdee1752a to your computer and use it in GitHub Desktop.
Save penglongli/a28e85520eb1827932d356dcdee1752a to your computer and use it in GitHub Desktop.
对比 switch 和 if 处理逻辑的代码清晰度
import static com.utils.TestSwitch.Fruit.*;
/**
* Created by Pelin on 17/2/20.
*/
public class TestSwitch {
enum Fruit {
APPLE, BANANA, POTATO
}
public static void main(String[] args) {
Fruit fruit = POTATO;
testSwitch(fruit);
testIf(fruit);
}
private static void testSwitch(Fruit fruit) {
switch (fruit) {
case APPLE: {
System.out.println("我拿到了苹果");
// 接下来是业务逻辑
break;
}
case BANANA: {
System.out.println("我拿到了香蕉");
// 接下来是业务逻辑
break;
}
case POTATO: {
System.out.println("我拿到了土豆");
// 接下来是业务逻辑
break;
}
default: {}
}
}
private static void testIf(Fruit fruit) {
if (fruit.equals(APPLE)) {
System.out.println("我拿到了苹果");
// 接下来是业务逻辑
} else if(fruit.equals(BANANA)) {
System.out.println("我拿到了香蕉");
// 接下来是业务逻辑
} else if (fruit.equals(POTATO)) {
System.out.println("我拿到了土豆");
// 接下来是业务逻辑
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment