Monday, August 1, 2011

CQ Simulation: Validating Input

Today, I want to add some data validation for the Seat class. There's two ways to do this – either the validation check simply fixes an error and lets the program go on, or it throws an exception, forcing the program to stop and the error to be dealt with.

This isn't envisioned as a program where users will be prompted for data. That means accepting bad data will ruin things anyway.

To split the difference, I decided to put it in debug code.

How about this:



#if DEBUG

if (numberOfSeats [LESSTHAN] 1) { throw new Exception(); }

if (timePerSeat [LESSTHAN] 1) { throw new Exception(); }

#endif


And some tests:


# Test data validation

try {

$testSimulation = new Simulation(0, 0)

"FAIL: Accepting bad data."

}

catch {}

try {

$testSimulation = new Simulation(1, 0)

"FAIL: Accepting bad data."

}

catch {}

try {

$testSimulation = new Simulation(0, 1)

"FAIL: Accepting bad data."

}

catch {}


I also added code validating other constructors that take integers as input.

Of course, I don't think all of these will be able to take input from users. Instead, they will only be called by other classes. Still, at this point, I don't know for sure whether there will be a chance to have it fail.

Next up: I'm going to tackle the order of actions in a tick. This will involve getting the basic simulation up and running.

No comments:

Post a Comment