Issue
I have to functions with exactly the same contents but different annotation values.
@MyAnnotation("valueA")
public void functionA() {
// exactly same code here
}
@MyAnnotation("valueB")
public void functionB() {
// exactly same code here
}
How can I refactor functionA and functionB, so that I can add more values such as "valueC" without creating a new functionC?
Solution
Helper methods. You still make these methods, but they are oneliners:
@MyAnnotation("valueA")
public void functionA() {
function0();
}
@MyAnnotation("valueB")
public void functionB() {
function0();
}
private void function0() {
// actual code here
}
Alternatively, you need to rewrite MyAnnotation.java
as well as the code that interacts with it. I assume you can't do that (that it is an external library), in which case the above is the only answer.
Otherwise, you can make the String value() default ""
line in MyAnnotation.java
be String[] value() default []
instead. Now you could write:
@MyAnnotation({"valueA", "valueB"})
public void functionBoth() {
// this is the sole method
}
Or you can make a multi-annotation so that you can write:
@MyAnnotation("valueA")
@MyAnnotation("valueB")
public void functionBoth() {
// this is the sole method
}
Answered By - rzwitserloot
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.