In these challenges, we will bring in validation on our fields in the constructor. If you have difficulty attempting these, don’t worry…we will cover this approach in detail in the next lecture.
Using Spot Version 3.0 as a starting point, save this as lab06_challenge_01.
In this code, you will notice we have the following Spot Constructor:
Spot(float xPos, float yPos, float diamtr){
xCoord = xPos;
yCoord = yPos;
diameter = diamtr;
}
We want to add some validation rules to this i.e.
before setting the diameter, check that the value sent into the constructor is between 20 and 50 inclusive. If the value sent in is outside that range, set a default value of 20.
before setting the xPos and the yPos, check that the value sent into the constructor is not negative (i.e. >= 0). If the value sent in is negative, set a default value of 0.
Test your code to make sure it is behaving appropriately.
Save your work and close the project.
If we add another field to Spot - a String field called spotName. (This simply stores the name of the spot). The class now looks like (without the validations done above):
class Spot{
String spotName;
float xCoord, yCoord;
float diameter;
Spot(String name, float xPos, float yPos, float diamtr){
spotName = name;
xCoord = xPos;
yCoord = yPos;
diameter = diamtr;
}
}
and the main class looks like:
Spot sp;
void setup()
{
size (100,100);
noStroke();
sp = new Spot( "SpottySpot", 33, 50, 30);
}
void draw()
{
background(0);
ellipse(sp.xCoord, sp.yCoord, sp.diameter, sp.diameter);
println(sp.spotName);
}
Create a new sketch called lab06_challenge_02 and cut and paste the above code into it.
Firstly, run this program. See how the code in the Spot class and the main class have changed to cater for the extra field. Can you explain why so many SpottySpot are printed to the console?
Then, add a validation to the constructor that only allows names that are no more than 7 characters long. If the name is too long, the constructor should impose the rule by cutting the spotName string to the first 7 characters.
Test your code to make sure it is behaving appropriately. In particular, perform the following tests:
enter a name that is 6 characters long…all 6 characters should be stored in the name.
enter a name that is 7 characters long…all 6 characters should be stored in the name.
enter a name that is 8 characters long…only the first 7 characters should be stored in the name (hint: substring).
NOTE: This is called boundary testing i.e. we are testing just below, exactly on, and just above the boolean condition that we used in the validation. This is a popular testing approach as a lot of bugs live in the boundaries.
Save your work and close the project.