[Quick Coding Tips] Using Variables Instead of Hard Coding

Using variables vs Hardcoding in VEXcode VR

  1. Readability and Ease of Modification
    When exploring programming, we always need to make changes to our programs. Coding with variables instead of hardcoding can significantly improve the readability of the code and make modifications much easier.

Let’s take a look at an example of hard coding: navigate the VR Robot to draw a square with a side length of 300 mm on the Art Canvas + Playground (Image 1).

If we want to change the side length to 500 mm, we’ll have to go through the program and modify all the drive forward for 300 mm instructions to drive forward for 500 mm (Image 2).

Alternatively, we can utilize a variable to program the robot to draw a square with a side length of 300 mm using the following steps:1. Define a variable to store the length of the square. 2. Set the value of the variable to 300. 3. Use the variable Reporter block as the parameter for the drive for block to code the robot to draw a square (Image 3).

Note: To use the variable Reporter block as the parameter for the drive for block, drag the variable Reporter block into the circle space of the drive for block.
Now if we wish to modify the code to instruct the robot to draw a square with a side length of 500 mm, we only need to update the value of the variable to 500. (Image 4)

  1. More Flexibility
    Incorporating variables in the program also offers greater flexibility, allowing it to adapt to changing requirements.
    In the following example (Image5), we use two variables, “Length” and “Sides”, to specify the number of sides and the length of each side of a polygon.

By making simple adjustments to the variable values, we can easily instruct the robot to draw a polygon with any desired number of sides and side lengths.

Drawing

In summary, using sensor data and variables over hardcoding is a powerful technique that enables the robot to adapt and respond effectively to changing requirements. It improves program readability, makes modifications easier, and enhances overall flexibility.

Please let us know if you have any questions, comments, or feedback. Thank you!

3 Likes

This is a really neat way to show the value of variables, and could be a great strategy for helping students to make some tricky math concepts a bit more concrete. I bet @Lauren_Harter could think of some really great math extensions or ways to use this in a math lesson!

2 Likes

Absolutely! The shapes being drawn remind me of this Interior Angle activity I wrote some code for in VR! I used variables and 2D lists :smiley:

4 Likes