Avoid switch! Use enum-1
DecemberRecently I was about to refactor some code Crap4j pointed me to. When I realized most of that code was some kind of switch-case or if-else-cascade, I remembered Daniel´s post and decided to obey those four rules.
This post is supposed to give some inspiration on how to get rid of code like:
01 | switch (value) { |
02 | case SOME_CONSTANT: |
03 | //do something |
04 | break ; |
05 | case SOME_OTHER_CONSTANT: |
06 | //do something else |
07 | break ; |
08 | ... |
09 | default : |
10 | //do something totally different |
11 | break ; |
12 | } |
or an equivalent if-else-cascade.
In a first step, let’s assume the constants used above are some kind of enum you created. For example:
1 | public enum Status { |
2 | ACTIVE, |
3 | INACTIVE, |
4 | UNKNOWN; |
5 | } |
the switch-case would then most probably look like:
01 | switch (getState()) { |
02 | case INACTIVE: |
03 | //do something |
04 | break ; |
05 | case ACTIVE: |
06 | //do something else |
07 | break ; |
08 | case UNKNOWN: |
09 | //do something totally different |
10 | break ; |
11 | } |
No comments:
Post a Comment