Skip to content

Add Commands.runIf #7807

@otter502

Description

@otter502

Is your feature request related to a problem? Please describe.
I often find myself writing command "logic" that will run a command if and only if a boolean supplier is true. There are ways of doing this in house but these methods aren't as readable or simple to debug as a dedicated Commands factory method would be.

Describe the solution you'd like
I think a good solution would be a version of the Commands.either() command which calls the boolean selector when the command is run and then runs the passed command if the selector returns true.

Describe alternatives you've considered
There are several methods to achieve the same result using the commands factory method but each would be larger or are going to have costs in other respects.
The two methods I've found are using Commands.defer(...) with a if statement in the command supplier and using Commands.either(...).

  • Commands.defer(...)
    • Doesn't use the ConditionalCommand class under the hood, instead using the DeferredCommand class
  • Commands.either(...)
    • This solution I'm proposing would do what commands.either() would do with its onFalse parameter set to Commands.none()

Additional context
Here is a rough idea of a potential solution (I did my best to follow the javadocs of the Commands.either method)

This assumes it's being run in the command factory class (Commands), if it's not then the this.either can be replaced with Commands.either

/**
   * Runs a command if the boolean selector function is true.
   *
   * @param selector the selector function
   * @param onTrue the command to run if the selector function returns true
   * @return the command
   * @see ConditionalCommand
   */
  public static Command runIf(BooleanSupplier selector, Command onTrue){
      return this.either(onTrue, Commands.none(), selector);
  }

This also follows the visual look of an if statement where the condition comes first then the code that'll run.

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: 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