As a homework project I have been asked to create a bunch of classes in a hierarchy, which take different parameters in their constructors, and allow a user to interactively create objects of such classes. For simplicity, let's assume that the classes are Base
and Child
, with Child
extending Base
. Any future class in the project would extend Base
or one of its subclasses.
Although the focus of the project is not writing elegant or maintainable code, I am trying write such code.
Ideally, after figuring out what object the user wants to instantiate, I would have a way of figuring out which parameters are necessary to create such an object and pass that list to the method in charge of retrieving them from the user. I had thought of a static method, getNecessaryArguments()
such as:
public class Base {
public static List<String> getNecessaryArguments() {
return Arrays.asList("name", "age");
}
public Base(String name, String age) {
...
}
}
public class Child extends Base {
public static List<String> getNecessaryArguments() {
final List<String> baseArgs = Base.getNecessaryArguments();
baseArgs.addAll(Arrays.asList("position"));
}
public Child(final String name, final String age, final String position) {
super(name, age);
...
}
I would then do something like UserInterface.requestParameters(XXX.getNecessaryArguments())
.
There are several obvious issues with this code, though:
- Two lists of arguments need to be maintained in parallel for each class: the actual arguments to the constructor and arguments returned by
getNecessaryArguments()
. - The class which
Child
extends has to be explicitly mentioned in itsgetNecessaryArguments()
, sincesuper()
cannot be used in static contexts.
This all opens up the possibility of out-of-sync issues if the design changes in the future.
What would be the best way of handling these issues so that the code can adapt to some design changes? I thought of reflection, but I think you cannot retrieve argument names from it, only the method signature.
Aucun commentaire:
Enregistrer un commentaire