I’m writing an eclipse plugin, where I want to contribute an action to the JDT package explorer. In order for the action to be executed, there must be two different files selected. Therefore I retrieve the active selection of the JDT package explorer in the command handler for that action. That is where my problem is.
Currently the code that extracts the selected files from IStructuredSelection involves multiple local variables with multiple if statements and multiple returns in about 30 lines of code. And of course this code looks at least a bit ugly.
What concept(s) and or patterns should I use to make this code more cleaner?
The eclipse platform recommends to use the adapter pattern. So I thought of creating a pojo like this:
public class FooCommandArgs {
private IFile xmlFile;
private IFile csvFile;
//getters and setters here ...
}
and creating the necessary adapters for it from IStructuredSelection. However doing this would just move the ugly code to some other places.
So as the field names suggest, each item I want to extract from the
IStructuredSelectionhas to fulfill some conditions. My idea is to use bean validation api for this. The pojo would then look like this:The
Validatorinterface of the bean validation api provides the method<T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups)which I could use for that. I just would have to introspect the java bean properties and then invoke that method for every combination of anIStructuredSelectionitem and pojo property. If the result is that every item could be assigned to a bean property with no constraint violations than I can just go on with handling the actual command. Ambiguities might as well be handled.EDIT:
I have implemented this suggestion and it works out quite nice. Using this technique, it is also very easy to explain to a user programmatically, why a certain command isn’t enabled or can not be executed.
I don’t want to forget to mention JCommander at this point, which is the inspiration for this idea.