Dave Drohan (SETU)

BACK NEXT

Challenges

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.

Challenge 1

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.

Test your code to make sure it is behaving appropriately.

Save your work and close the project.

Challenge 2

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:

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.