Lesson 29: Modifying WPI Libraries / Building Wrappers

Sometimes the library class you are given is not quite the interface you want for your robot. A wrapper is a class that surrounds another class and gives the rest of your code a cleaner way to use it.

Why Wrap?

Wrappers can make code easier to read, hide repeated setup, enforce safety limits, and let you swap hardware without changing every file.

public class SafeMotor {
    private SpeedController motor;
    private boolean inverted;

    public SafeMotor(SpeedController motor, boolean inverted) {
        this.motor = motor;
        this.inverted = inverted;
    }

    public void set(double speed) {
        if (speed > 1.0) {
            speed = 1.0;
        } else if (speed < -1.0) {
            speed = -1.0;
        }

        motor.set(inverted ? -speed : speed);
    }
}

Do Not Hide Too Much

A wrapper should make a common task clearer. It should not make the hardware impossible to understand. If a new student cannot tell what object is being controlled, the wrapper may be too clever.

Prefer Small Interfaces

Expose what the robot actually needs. A drive class might have tankDrive(), stop(), and getAverageDistance(). Other code does not need direct access to every motor method.

Practice

Write a wrapper around a limit switch that has a method called isPressed(). If your switch wiring returns false when pressed, hide that inversion inside the wrapper.