Java enums are much more powerful than simple lists of constants. They can have fields, methods, constructors, and even implement interfaces. This allows you to encapsulate both data and behavior for each enum constant, making your code more robust, readable, and maintainable.
- State Machines: Represent subsystem states (e.g., elevator positions, intake modes) with associated data and logic.
- Configuration: Store configuration values or strategies for each mode.
- Behavior Encapsulation: Attach methods to enum constants for state-specific behavior.
- Type Safety: Prevent invalid states and reduce bugs compared to using raw ints or strings.
@Getter
@RequiredArgsConstructor
public enum SuperstructureState {
ALGAE_L2_CORAL(SuperstructureStateData.builder().pose(...).build()),
ALGAE_L3_CORAL(SuperstructureStateData.builder().pose(...).build());
// ...
private final SuperstructureStateData value;
}- Add Fields: Store configuration or state data for each constant.
- Add Methods: Implement logic that varies by state (e.g., isScoring(), getTargetHeight()).
- Implement Interfaces: Allow enums to be used polymorphically (e.g., as a CommandSupplier).
- Use in Switch Statements: Drive subsystem logic based on enum state.
enum IntakeGoal {
INTAKE(1.0),
OUTTAKE(-1.0),
HOLD(0.2);
private final double voltage;
IntakeGoal(double voltage) { this.voltage = voltage; }
public double getVoltage() { return voltage; }
}
// Usage:
intakeMotor.set(intakeGoal.getVoltage());public interface StateBehavior { void execute(); }
public enum ElevatorState implements StateBehavior {
BOTTOM { public void execute() { moveToBottom(); } },
TOP { public void execute() { moveToTop(); } };
}- Use enums for all subsystem and robot states.
- Attach relevant data and logic to each constant.
- Avoid using raw ints or strings for state.
- Use @Getter/@RequiredArgsConstructor (Lombok) to reduce boilerplate.
- Using enums as mere constants (add fields/methods for power!)
- Duplicating logic in switch statements instead of using enum methods
- Using magic numbers or strings for state
- Refactor int/string states to enums.
- Move state-specific logic into enum methods.
- Use enums in command factories and state machines.
public enum AutoMode {
FOUR_PIECE("Four Piece", () -> new FourPieceAuto()),
TWO_PIECE("Two Piece", () -> new TwoPieceAuto());
private final String name;
private final Supplier<Command> commandSupplier;
AutoMode(String name, Supplier<Command> commandSupplier) {
this.name = name;
this.commandSupplier = commandSupplier;
}
public Command getCommand() { return commandSupplier.get(); }
}