Monday, July 4, 2011

CQ Simulation: DataUser Design

I've been away from this blog too long -- it took me a while to warm up and start getting things done.

Today, I started in on the DataUser class. This class models a single data user as it comes into line, waits, gets a computer, uses the computer, and leaves.

I may have to include more state information -- for after the user is done -- but for now, this is the fields:

// FIELDS
private int queueUpTime; // The number of the tick at which this user joins the line.
private int patienceTime; // The number of ticks that this user is willing to wait.
private int desiredTime; // How many ticks the user want to use the computer.
private bool sitting = false;

The constructor is trivial, just taking three ints and assigning them to the first three values.

When the user gets to sit down, the state (represented by sitting) changes. Here's the code for that:

public void sitDown()
{
sitting = true;
}

And I don't write code without writing tests for it:

$testSitting = new DataUser (100, 100, 100)
if ($testSitting.testSitting()) { "FAIL: sitting variable should be false." }
$testSitting.sitDown()
if (!($testSitting.testSitting())) { "FAIL: sitting variable should be true." }

Next, I need code to change the values of the user's patience (decreasing as the user waits in line) and the time the user will use the computer (decreasing as the user uses the computer.)

public void tick (int thisTick)
{
if (thisTick LESS_THAN queueUpTime) return;
if (sitting) { patienceTime--; }
else { desiredTime--; }
... }

Notice that the system doesn't make these changes unless the user is in line.

I wanted to make sure that there were no negative values for these variables, so I included some testing code:

public void tick (int thisTick)
{
if (thisTick LESS_THAN queueUpTime) return;
if (sitting) { patienceTime--; }
else { desiredTime--; }
#if DEBUG
if (queueUpTime LESS_THAN 0) { throw new Exception(); }
if (patienceTime LESS_THAN 0) { throw new Exception(); }
if (desiredTime LESS_THAN 0) { throw new Exception(); }
#endif
}

I guess it wouldn't hurt if this were included in final code - just looks ugly. Other parts of the design might make this irrelevant, so I'll just leave it.

And here is the testing code:

$testTick = new DataUser (7, 10, 10)

try
{
for ($a = 0; $a -lt 25; $a++) {
$testTick.tick(9)
}

"FAIL: Test code should throw an exception for a negative value."
}
catch { }

$testTick = new DataUser (7, 10, 10)
$testTick.sitDown()
try
{
for ($a = 0; $a -lt 25; $a++) {
$testTick.tick(9)
}

"FAIL: Test code should throw an exception for a negative value."
}
catch { }

This code tests that there is a decrement and that decrementing too far breaks the system. I don't like the idea that I'm testing two things at once. Let me go play with that a bit.

But this will do for today.

No comments:

Post a Comment