Methods, Classes, and Helpers
Extract repeated robot behavior into names that teammates can reuse.
Extract repeated robot behavior into names that teammates can reuse.
In this lesson, you will:
Methods turn repeated code into one named behavior. Classes group related data and behavior so an OpMode can read like robot intent rather than a pile of hardware writes.
The mental shift is from lines of code to robot verbs. setDrivePower, applyDeadband, stopDrive, and mapHardware describe what the robot is doing. When the code has verbs, students can review it without tracing every motor line.
Extract one helper at a time. First move duplicate motor writes into setTankPower or setMecanumPower. Then move joystick cleanup into a deadband method. Only then introduce a class that owns the helpers.
MethodsClassesandHelpers.javaJava
private double deadband(double value) {
return Math.abs(value) < 0.05 ? 0.0 : value;
}
private void setTankPower(double left, double right) {
left = Math.max(-1.0, Math.min(1.0, left));
right = Math.max(-1.0, Math.min(1.0, right));
leftMotor.setPower(left);
rightMotor.setPower(right);
}Helpers can hide bugs if they are not tested. Print the values entering and leaving a helper during the first test. If one helper is wrong, every caller will fail the same way, which is still better than five inconsistent copies.
Refactor a TeleOp so the main loop contains no raw motor setPower calls. All drivetrain writes must go through one helper method.
Check your understanding before moving on.
0 of 2 answered