Lesson 5: Keeping Track of Variables
As we get into more complicated topics and learn new things, our robot code is going to become larger and larger. Many things will be going on at once, and in order to keep our code clean and understandable, we need to have some organization. The focus of this lesson is going to be organizing all of your static number values (such as motor ports, calibration data, etc.).
Oftentimes, you will come back to a piece of code after not reading it for a while. If this code was written poorly, you may not understand how it works or what it does. In Lesson 3, you created a motor controller that took an integer value that represented the port on the roboRIO for that motor controller. It is not a good idea to simply put that number directly into the constructor because it decreases the overall quality of your code.
We can solve this problem by putting all of these values in one place. That
way, we know where they are if we ever need to change them and it also makes our
code cleaner. I recommend making two classes for this purpose: a
Wiring
class and a Calibration
class. In the wiring
class, we can store PWM ports, digital input ports, analog input ports, relays,
etc. In the calibration class, we can store values that never change but we
need to know nonetheless. (An example could be how many encoder ticks it takes
to move a lift all the way from bottom to top.) You may be thinking that this
sounds like ridiculous overkill, but as your code becomes larger you will lose
track of where all these numbers are coming from if you don't keep them
organized.
Here are the Wiring
and Calibration
classes from
Code Red's 2015 robot code:
Wiring.java
:
Calibration.java
:
Hopefully now you realize why it can be useful to store all these values in
one place. If we ever needed to change one of them, we don't need to hunt it
down: we know exactly where it is. Remember if these variables have the
public static
modifiers on them, that means we can access them from
anywhere without having to create any instances. For example, here is how the
Lesson 3 motor controller constructors should look now:
Take some time to convert your current code to use Wiring and Calibration
classes. You shouldn't have any arbitrary numbers going into constructors if you
don't have to. It is worth it to note however: don't go overboard. There are
some instances where using an arbitrary number is OK. For now you can leave
your Joystick
constructor alone, as there isn't a very good place
to put that number.
In the next lesson we are going to learn one more organization tactic, then we will move on to sensors!