Created
February 20, 2017 09:35
-
-
Save penglongli/a28e85520eb1827932d356dcdee1752a to your computer and use it in GitHub Desktop.
对比 switch 和 if 处理逻辑的代码清晰度
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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