Android
Kitkat이상, switch 문에서 String 을 이용하기
StanleyKou
2015. 8. 18. 16:35
Android 4.4 버전 (KitKat API 19) 부터는 Java 1.7 버전이 지원됩니다.
즉, switch 문에서 String을 이용할 수 있습니다. 덕분에 크게 가독성을 올릴 수 있게 되었는데요,
예를 들면 이런 if - else 로 가득한 코드가 있다고 가정해 봅시다.
String case1 = "00002a19-0000-1000-8000-00805f9b34fb";// "Battery Level"
String case2 = "00002a49-0000-1000-8000-00805f9b34fb";// "Blood Pressure Feature"
String case3 = "00002a35-0000-1000-8000-00805f9b34fb";// "Blood Pressure Measurement"
String case4 = "00002a38-0000-1000-8000-00805f9b34fb";// "Body Sensor Location"
String inputUuid = "00002a35-0000-1000-8000-00805f9b34fb";
if (inputUuid.equals(case1)) {
// Do something
} else if (inputUuid.equals(case2)) {
// Do something
} else if (inputUuid.equals(case3)) {
// Do something
} else if (inputUuid.equals(case4)) {
// Do something
}
수많은 if-else는 가독성을 크게 해치는데요, 이걸 제거할 필요가 있습니다.
(어차피 String compare가 들어갈 것이기 때문에, 수행속도 면에서는 동일할 것으로 생각됩니다)
이럴 때, 아래와 같이 코딩을 할 수 있습니다. 단, OS버전 등 위에서 언급한 조건이 충족되지 않으면 쓸 수 없습니다.
final String case1 = "00002a19-0000-1000-8000-00805f9b34fb";// "Battery Level"
final String case2 = "00002a49-0000-1000-8000-00805f9b34fb";// "Blood Pressure Feature"
final String case3 = "00002a35-0000-1000-8000-00805f9b34fb";// "Blood Pressure Measurement"
final String case4 = "00002a38-0000-1000-8000-00805f9b34fb";// "Body Sensor Location"
String inputUuid = "00002a35-0000-1000-8000-00805f9b34fb";
switch (inputUuid) {
case case1:
// Do something
break;
case case2:
// Do something
break;
case case3:
// Do something
break;
case case4:
// Do something
break;
}
라인 수는 더 길어 보입니다. 하지만, 1) 코드 량 자체가 훨씬 적고, 2) if문에서 오타가 날 확률도 적습니다.
참조: http://stackoverflow.com/questions/14367629/android-coding-with-switch-string