Reputation: 6546
Given the following code:
public interface DTMFKeys {
public String getKeyStr();
public static enum Sign implements TahoeDTMFKeys {
SIGN_1("*1"), SIGN_2("*2"), SING_3("*3"), SIGN_4("*4"), SIGN_5("*5"), SIGN_6(
"*6"), SIGN_7("*7"), SIGN_8("*8"), SIGN_9("*9");
private String keyStr;
private Sign(String keyStr) {
this.keyStr = keyStr;
}
@Override
public String getKeyStr() {
return keyStr;
}
}
public static enum Pound implements TahoeDTMFKeys {
POUND_1("1#"), POUND_2("2#"), POUND_3("3#"), POUND_4("4#"), POUND_5(
"5#"), POUND_6("6#"), POUND_7("7#"), POUND_8("8#"), POUND_9(
"9#");
private String keyStr;
private Pound(String keyStr) {
this.keyStr = keyStr;
}
@Override
public String getKeyStr() {
return keyStr;
}
}
}
How do I remove the duplicated code:
private Sign(String keyStr){
this.keyStr=keyStr;
}
@Override
public String getKeyStr() {
return keyStr;
}
Upvotes: 0
Views: 104
Reputation: 2840
it is nor possible nor desirable to remove these. since enums can't inherit from abstract classes it is not possible. keyStr
is a private concept both to Pound and Sign classes which both are indepented conceptually from each other.
Upvotes: 1
Reputation: 1247
It's not much code, so I wouldn't really worry about refactoring it away. Java enums can't extend other classes. Avoiding duplication in code is really about large amounts of complicated logic being repeated, not getter/setter fields.
If you're really worried about the 'duplication', you could do away with enums altogether?
public static String getKeyString(int n, char sign) {
if (n < 0 || n > 9) throw new IllegalArgumentException();
if (sign == '#') {
return ""+n+sign;
else if (sign == '*') {
return ""+sign+n;
else {
throw new IllegalAgumentException()
}
}
Also, SING_3 is spelled incorrectly.
Upvotes: 1