This is how my team has been building TimedRobot programs for a few years now, but I was learning about all sorts of fancy stuffs in Java (instance vars, class fields, statics, finals, constructors, super, etc.). Are there any important differences in where variables are initialized and how constructors are used in a TimedRobot program?
Standard Code
public class Robot extends TimedRobot {
private int num;
private Victor m_motor;
private Climber m_climber; // a class we created ; see below
@Override
public void robotInit() {
num = 10;
m_motor = new Victor(0);
m_climber = new Climber();
m_climber.climberInit();
}
}
public class Climber {
private Victor m_otherMotor;
public void climberInit() {
m_otherMotor = new Victor(1);
// Assume that we know better than to have conflicts from
// multiple Victors allocating the same PWM Port resource...
}
}
Given the above example code, is there any reason we can’t declare and initialize the int, Victor, and Climber in the class rather than in robotInit()
like so:?
Single-Line Declaration/Initialization
public class Robot extends TimedRobot {
private int num = 10;
private Victor m_motor = new Victor(0);
private Climber m_climber = new Climber();
@Override
public void robotInit() {
m_climber.climberInit();
}
}
Further, is there any reason we should be declaring a separate climberInit()
method when we could just use the object constructor like so:?
Using Constructor
public class Climber {
private Victor m_otherMotor;
public Climber() {
m_otherMotor = new Victor(1);
}
}
We were basing it off of the use of robotInit()
in TimedRobot. But furthermore, can’t we also apply single-line declaring/initializing here?
No Constructor; Just Declare/Initialize
public class Climber {
private Victor m_otherMotor = new Victor(1);
}
Because that would result in the next code, which is short, simple, and easy to read and understand. I know in the outside world, variables can be initialized with the declaration in Java, but in the TimedRobot file, the comment right before robotInit()
is This function is run when the robot is first started up and should be used for any initialization code.
So is there a reason to not initialize before robotInit()
?
Final Condensed Code
public class Robot extends TimedRobot {
private int num = 10;
private Victor m_motor = new Victor(0);
private Climber m_climber = new Climber();
@Override
public void robotInit() {
// empty and sad
}
}
Especially because we can reset variables to desired values when calling autonomousInit()
and teleopInit()
, which always run before autonomousPeriodic()
and teleopPeriodic()
. Obviously it’s not the same when we come to robotInit()
and robotPeriodic()
.
Has anyone looked into this, or can point me to a prior discussion or documentation of this, or have I gone too far into Java and broken it?