Java / refactoring switch case
•
Java
I tried to reconstruct the next case:
class Gen{
public void startClick(A a,B b,List<C> lstC,SortX sort){
for (int i=0; i<lstC.size(); i++){
try{
// some code with try and catch statement
switch (sort){
case SortA:
newOne(a,b,lstc);
break;
case SortB:
otherfunction(a);
break;
case SortC:
someotherfunction(lstC,a);
break;
}
}
} catch (Exception e){ //some code}
}
}
I try to create objects and process them, as we can see here: http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism
So I created an object: sortoftype, and then for each case, I also created an object (sorta, sortb, sortc) The function in sortoftype gets the instance of Gen and other sort objects What I failed to do was to call the sortoftype of the class Gen What shall I do? Is this refactoring possible?
Solution
You can define an interface to call when an operation is required
public interface SortX {
public void startClick(A a,C c);
}
public enum SortAEnum implements SortX<A,B,C> {
SortA {
public void startClick(A a,C c) {
newOne(a,c);
}
},SortB {
public void startClick(A a,C c) {
otherfunction(a);
}
},C c) {
someotherfunction(c,a);
}
}
}
public static void startClick(A a,List<C extends OnClick> lstC,SortX sort){
for (int i=0; i<lstC.size(); i++){
sort.startClick(a,lstC.get(i));
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
