Let’s consider the following code snippets:
1 2 3 |
public enum Currency { EUR, USD } |
1 2 3 4 5 |
String currency = "EUR"; if(Currency.EUR.name().equals(currency)){ System.out.println("Transfer permitted"); } |
How often do we see much the same scenario? It is not completely wrong since there is a try to use enums so it is not entirely “string driven” programming. However there is still a space to do some refactoring.
What about doing such stuff more in the object-oriented way? Enums are very powerful Java feature but for most of the cases there are only used in the simplest possible way.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public enum Currency { EUR() { @Override public boolean isTransferPermitted() { return true; } }, USD() { @Override public boolean isTransferPermitted() { return false; } }; public abstract boolean isTransferPermitted(); } |
1 2 3 4 5 |
Currency currency = Currency.valueOf("EUR"); if(currency.isTransferPermitted()){ System.out.println("Transfer permitted"); } |
In my opinion, refactored code is clearer and more self-documenting then the original one. Generally speaking it is a Template Method design pattern applied to Java enums.