dimanche 23 février 2020

How to programatically retrieve the arguments for a method

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:

  1. Two lists of arguments need to be maintained in parallel for each class: the actual arguments to the constructor and arguments returned by getNecessaryArguments().
  2. The class which Child extends has to be explicitly mentioned in its getNecessaryArguments(), since super() 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