Class CommonParameters


  • public final class CommonParameters
    extends java.lang.Object
    Commonly used parameters that can be reused in multiple commands.

    The intent behind these parameters is to reduce the amount of boilerplate used when creating commands and retrieving elements. A general workflow for defining a command with a ServerPlayer parameter may look like this:

     
     final Parameter.Value<ServerPlayer> parameter = Parameter.player().setKey("player").build();
     final Command.Parameterized builder = Command.builder()
          .parameter(parameter)
          .executor(context -> {
              context.sendMessage(Component.text(context.requireOne(parameter).getName()));
              return CommandResult.success();
          }).build();
     // registration happens here.
     

    While this is a totally valid approach, there are two particular considerations that can be made:

    • Sponge provided ValueParameters and, by extension, Parameter.Values are stateless and so can be reused by multiple commands, or indeed, multiple times within the same command; and
    • Due to the type safety provided by the CommandContext and the requirement of retrieving parsed arguments by the Parameter.Key (or the actual Parameter.Value, which implements this key, plugin developers will either need to keep a reference to the parameter value, its key, or rebuild the key as required (paying close attention to the Parameter.Value type).

    Given these two considerations, it generally makes sense to store one Parameter.Value for a given ValueParameter and Parameter.Key combination. Further, it is clear that plugins will tend to use similar, if not the same, parameter/key combinations.

    The values held by this class are commonly used Parameter.Values with sensible key names such that plugin developers do not have to generate their own parameters and can also use these as Parameter.Keys when obtaining results from the CommandContext. The example above would then become:

     
     final Command.Parameterized builder = Command.builder()
          .parameter(CommonParameters.PLAYER)
          .executor(context -> {
              context.sendMessage(Component.text(context.requireOne(CommonParameters.PLAYER).getName()));
              return CommandResult.success();
          }).build();
     // registration happens here.
     

    reducing object creation and slightly reducing repetition amongst commands that use the same parameters.