【收藏】Avoid switch! Use enum!

今天看到一篇关于怎样避免使用switch而用enum的文章,看了以后感觉作者想法挺好的,这里共享出来。

 

原文地址:Avoid switch! Use enum!

Recently 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:

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:

the switch-case would then most probably look like:

In this case you don’t need the switch-case at all. Instead, you can tell the enum to do all the work:

The switch-case then shrinks to:

But what if the constants are defined by some third-party code? Let’s adapt the example above to match this scenario:

Which would result in a switch-case very similar to the one above and again, you don’t need it. All you need to do is:

Regarding this case there is a small stumbling block, which you have to pay attention to. Enum.values() returns an Array containing the elements in the order they are defined, so make sure that order accords to the one of the constants. Furthermore ensure that you do not run into an ArrayOutOfBoundsException . Hint: Time to add a test.

There is yet another case that may occur. Let’s pretend you encounter some constants that aren’t as nicely ordered as the ones above:

To cover this case, you need to alter the enum to look something like:

Even though this introduces an if (uh oh, didn’t obey rule #4), it still looks much more appealing to me than a switch-case or if-else-cascade would. Hint: Time to add another test.

How do you feel about this technique? Got good or bad experiences using it?

 

 

 

 

 

 

 

 

 

 

 

 

 

 


你可能感兴趣的:(switch)