Skip to content

Give Command an additional protected constructor to enable a new command definition pattern with improved syntactic sugar #8551

@cwm9cwm9

Description

@cwm9cwm9

Command helpers are great until you need per-instance state, at which point you usually make a new class. To keep the interface consistent, you might then add a class factory for the new class, paralleling the return of instantiated helper classes.

I'd like to propose a new pattern for the writing of new commands that mimics and improves upon the syntactic sugar of the helper classes.

All that is required is to give Command a new constructor overload:

  protected Command(Subsystem... requirements) {
    this();
    addRequirements(requirements);
  }

Once this is done, Command becomes cleanly extendable via anonymous classes, like this:

    public Command cmdSomeCommand() {
        return new Command(this) {
            private double newVariable;
            @Override public void initialize() { newVariable=0; }
        }.withName("myNewCommand");
    }

This pattern allows users to add new fields and override exactly the methods they wish in the same way they would when extending CommandBase, while simultaneously allowing the immediate instantiation of the class in the exact way Helper classes currently do.

An additional advantage of this pattern is that it eliminates the mixed use of

    Command command1 = cmdSomeCommand();
    Command command2 = new SomeCommand2();

which can happen when users don't implement a class factory.

Metadata

Metadata

Assignees

No one assigned

    Labels

    component: command-basedWPILib Command Based Librarytype: featureBrand new functionality, features, pages, workflows, endpoints, etc.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions