Tuesday, August 30, 2011

CQ Simulation: Fixing the HasAbandoned Problem

So, I've been struggling with some code for the last couple of weeks. My problem was that I was using a foreach loop in a context where the contents of the loop might change the iteration list.

Because foreach loops do not guarantee the order in which things are done, it's not valid to have the list change halfway though.

My solution – or hack – was to assign each member of the list that matched a certain criterion – the “has abandoned” method – to a second list and then cycle through the second list, deleting items from the first list.

Here's the code:


private List[LESSTHAN]DataUser[GREATERTHAN] tempList;

...

public void tick()

{


...

foreach (DataUser a in computerQueue) {

a.tick(simTick, results);

if (a.hasAbandoned(simTick))

{

tempList.Add(a);

}

}


...

foreach (DataUser d in tempList)

{

computerQueue.Remove(d);

}


As I implied, it seems like a hack to me.

The real problem, I suppose, is that I used C# lists which don't play nicely with foreach in these circumstances.

But I don't want to re-architect the thing, so let's leave well enough alone and go back to working on the program.

Tuesday, August 23, 2011

CQ Simulation: More Tests 2

More method tests today.

I wanted to make sure that these tests are testing the methods themselves, without mixing up the different things to be tested. This means some of these are quite boring:


# Test the timeLeft method


$testSeat = new Seat(60)

if (!($testSeat.timeLeft())) {"FAIL: Time Left should be true."}


Well, maybe there's more later, but for now, next: DataUser constructor:


# queue up time, patience time, desired time.

$testDataUser = new DataUser(1, 2, 3)


And now for 0 values:


$testDataUser = new DataUser(0, 0, 0)

This one caused an exception. Just one problem – well, look at the code:


if (queueUpTime [LESSTHAN] 0) { throw new Exception(); }

if (patienceTime [LESSTHAN] 0) { throw new Exception(); }

if (desiredTime [LESSTHAN] 0) { throw new Exception(); }

Zero is not less than zero. Here – let's try something:


// if (queueUpTime [LESSTHAN] 0) { throw new Exception(); }

// if (patienceTime [LESSTHAN] 0) { throw new Exception(); }

// if (desiredTime [LESSTHAN] 0) { throw new Exception(); }

Same error:

New-Object : Exception calling ".ctor" with "3" argument(s): "Exception of type 'System.Exception' was thrown."

I suspected as much. It seems there is another place in the code that is throwing this exception.

Oh, I was looking at the wrong place in the code. Here's the code for verifying the constructor:

if (X_queueUpTime [LESSTHAN] 0) { throw new Exception(); }

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

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

So, let's make this into an expected fail and we're done.

try {

$testDataUser = new DataUser(0, 0, 1)

"FAIL: Accepting input outside acceptable range."

} catch {}


try {

$testDataUser = new DataUser(0, 1, 0)

"FAIL: Accepting input outside acceptable range."

} catch {}

More next time.


Monday, August 22, 2011

CQ Simulation: Revising and Extending Tests

Over the last couple of weeks, I've letting coding get ahead of testing. The point of this methodology – with testing proceeding at the same time as coding – is to let the testing inform the coding.

I've decided to get back to it. I'm going to make sure I have tests for each method and constructor. I'm also going to make sure they are in files that are clearly named and have enough comments to follow the intent.

For instance, here is ClassSeatConstructor.ps1:

# Testing Seat Constructor

#

#

# Expected success:


$testSeat = new Seat(60)



# Test the Free property: On creation, should be Free.


$testSeat.Free = $true

if (!($testSeat.Free)) {"FAIL: Free should be True."}


$testSeat.Free = $false

if ($testSeat.Free) {"FAIL: Free should be False."}



# unacceptable values: 0, -1



try {

$testSeat = new Seat(0)

"FAIL: Invalid value did not cause exception."

}

catch {}

try {

$testSeat = new Seat(-1)

"FAIL: Invalid value did not cause exception."

}

catch {}


This script verifies that the constructor works. The initial state of the object has Free = True.

Then it tests to see that two unacceptable values are not permitted.

That test relies on testing code, so I should note that in the script.

What this test doesn't do is verify that the initial value is assigned. That will involve more testing code:

public int getUseTime()

{

return useTime;

}


And the test:

#verify initial state:

#USES TESTING CODE


$testSeat = new Seat(20)

if (!($testSeat.getUseTime() -eq 20)) {"FAIL: Initial state of Seat object should be 20."}


One down, 16 to go.

Friday, August 19, 2011

CQ Simulation: Troubleshooting the Tick Method

A couple of days back, I sat down to do one of these posts and I hit a brick wall. I was getting, well, here's the error:

Exception calling "tick" with "0" argument(s): "Collection was modified; enumeration operation may not execute."

This is the same error I was getting when I was removing objects from the computer queue during a foreach loop. I didn't understand why it was happening again because I wasn't removing anything from a list, so it shouldn't have invalidated an enumeration action.

But then I read on-line that some list classes have a “dirty” flag – and my code has the following line:

c.Free = false;

And if I comment this line out, the error doesn't happen. (although that messes up other stuff.)

So, I might be able to fix it by implementing it as a for-loop.


And it still doesn't work.

Well, I'll have to figure it out next time.

Wednesday, August 17, 2011

CQ Simulation: Testing the tick() Method

I sat down to write a simpler test for populating a seat. Here's the draft code:

# Test whether users are being assigned to seats.


$testSimulation = new Simulation(6, 30) # 6 seats at 30 minutes each


# Populuate the ComputerQueue list


for ($i = 0; $i -lt 25; $i++)

{

$testDataUser = new DataUser(($i+1), 100, 100) # large values for patience and time desired.

$testSimulation.takeUser($testDataUser)

}


$testSimulation.queueSize()

$testSimulation.tick()

$testSimulation.queueSize()

$testSimulation.tick()

$testSimulation.queueSize()

$testSimulation.tick()

$testSimulation.queueSize()

$testSimulation.tick()

$testSimulation.queueSize()

$testSimulation.tick()

$testSimulation.queueSize()

$testSimulation.tick()

$testSimulation.queueSize()


$testSimulation.tick()

$testSimulation.queueSize()


$testSimulation.tick()

$testSimulation.queueSize()


$testSimulation.tick()

$testSimulation.queueSize()


$testSimulation.tick()

$testSimulation.queueSize()


I expected this to fill the six seats and then spin its wheels. Like this:


25

24

23

22

21

20

19

19

19

19

19


Didn't happen. Instead, it just kept counting down.

So, is the code right or is the test right?

Looking at the code, there's no place where the seat is changed to no longer free. This is what I meant when I said I didn't like how complicated the tick() method was here.

I added a method that takes the DataUser and resets the Free value:


public void takeSeat(DataUser x)

{

currentUser = x;

Free = false;

}


And last thing for right now: Does the Seat class free up seats, as it should? I could inspect the code, but a test would be easier:


for ($1 = 0; $i -lt 200; $i++)

{

$testSimulation.tick()

$testSimulation.queueSize()


}


This works great – until the number of users reaches zero. Then I get an error from the code.

And I'll fix that next time.

Monday, August 15, 2011

CQ Simulation: Fixing Assigning Users to Seats

I want to do two things in the next few days:

  • Add the current tick to the Results class. Since I'm passing the results object back and forth between classes and since some of the results will need to know what time it is in the simulation, it seems to make sense.
  • Fix the assigning of users to seats so that it respects the time of the simulation. (Per the last post.)

After that, I want to take a break from working on functionality to do some infrastructure work:

  • Clean up the method tests and get them all in documented files.
  • Fill in any method tests that haven't been written (as well as constructor tests, if necessary).
  • Code-level documentation for all classes.
  • Change the names of variables. I picked some really, really confusing names.

I didn't do code-level docs yet because the code has been in flux. Now that the basic methods have been laid out, I can document method signatures.

Today: Assigning users to seats.

Here's my first run at the code:

foreach (Seat c in seats) {

if (c.Free) {

if (computerQueue.Count [GREATERTHAN] 0) {

foreach (DataUser e in computerQueue) {

if (e.QueueUpTime [GREATERTHAN]= simTick) {

c.currentUser = e;

computerQueue.Remove(e);

}

}

}

}

}

(And I HATE how complicated this looks.)

Let's see if it works.


Except for one typo that I just fixed, it compiled. It does fail one test. Hold on a second.

Oops – since the Remove method changes the list, it can't proceed through the foreach loop.

Actually, I don't want it to. I wonder if I can just slip in a break statement.

Ah, that fixed the coding problem, but it still leaves the wrong test result. That is, the simulation is still consuming 6 of the users when it should not consume any on the first tick.

Ah – I put in [GREATERTHAN]=, not [LESSTHAN]=. Fixing that fixes the problem.

Tomorrow, I'll write a better test for this.


Thursday, August 11, 2011

CQ Simulation: More Tests

I need to spend a longer session getting organized, again, on this project. Lately, I've been accomplishing a certain amount of coding, but I'm not sure where it's all headed.

And the way that I generally organize things is by building tests.

I started out with the operational test I did earlier. This test is designed to run the simulation as it is intended to run.


# create simulation with 6 seats at 30 minutes per seat.

$testSimulation = new Simulation(6, 30)


I added 12 users and then did the following test:


$testSimulation.queueSize()

$testSimulation.tick()

$testSimulation.queueSize()


One tick should only advance the simulation by one tick and none of my users joined the queue at time 0 or 1, so one tick should have no effect on the (user) queue size.

But it did. The results were 12 then 6.

Which means that half the users got to sit down.

Which means the code is broken.

WAIT: I don't want to jump to conclusions. If the users are going away by sitting down, instead of by having the abandon mechanism broken, then I can change the number of seats to 5 and get first 12 then 7.

That prediction was correct, so I'm betting the problem is in the tick method of the simulation class.


OK, reviewing the code, the way I wrote it, it relies on the list being ordered by time when the user queues up and it doesn't check whether a user has queued up.

I'll start fixes next time.

Tuesday, August 9, 2011

CQ Simulation: Implementing Results

Had to fight a bit with this.

I wrote some code to kick a user off a seat when the time ran out:

if (useTime == 0)

{

currentUser = null;

this.Free = true;

}

This kept giving me a FAIL on the tick method for Seat. Here's the test.


#test when seat occupied

$testSeat = new Seat(60)


$testSeat.Free = $false


for ($a = 0; $a -lt 59; $a++) {

$testSeat.tick()

}


if (!($testSeat.timeleft())) { "FAIL: Time left should still be above 0."}



$testSeat.tick()



if ($testSeat.timeleft()) { "FAIL: Tick method should have reduced time left to 0."}


I was sure something was wrong, but I took a closer look at my test – and it's no longer valid. Once tick is called when the user has no time left, the tick method now resets the time to the original amount.

I marked the test as no longer valid.


Next up, I added some code to interact with the results object. Here's some:


if (d.hasAbandoned(simTick))

{

computerQueue.Remove(d);

results.incrementAbandonded();

}


This method, in addition to removing an expired datauser object, now increments the results object.

The increment method is trivial:


public void incrementAbandonded()

{

usersAbandoned++;

}

And that will do it for tonight.

Next time, I'll do the rest of the results recording. That should give me the basic functionality of the program.

Monday, August 8, 2011

CQ Simulation: Going through the DataUser List

A couple of days back, I wrote code that walked through the seats list and found any empty seats. It then went to get a user to fill the empty seat, if possible.

Today, I did the same for the users – that is, I wrote code that goes through the user list and removes any user that have abandoned waiting.

Here's the code in the DataUser class:


public bool hasAbandoned(int x)

{

if (x [GREATERTHAN] (queueUpTime + patienceTime)) return true;

return false;

}


This compares the current tick to the time the user is willing to wait plus the time when the user started waiting.

Here's the code in Simulation that checks this and, if necessary, removes the object from the list:


foreach (DataUser d in computerQueue)

{

if (d.hasAbandoned(simTick)) computerQueue.Remove(d);

}


I haven't been writing many tests lately. I want to get the thing running and then refine it. After all the pieces are there (hopefully by the end of the week), I want to spend some time cleaning it up and documenting it.

Sunday, August 7, 2011

CQ Simulation: A Results Class

So, here's code to fix the problem from yesterday:


foreach (Seat c in seats) {

if (c.Free) {

if (computerQueue.Count [GREATERTHAN] 0) {

c.currentUser = computerQueue[0];

computerQueue.RemoveAt(0);

}

}

}


I could move the conditional outside the foreach statement, meaning that the system would not bother trying to fill seats if there were no users to fill them with.

Oh, that wouldn't work – what if there was one user waiting and two seats to fill?

So, the current version passes the existing tests.

At this point, there's no reporting of results. I'm going to start tackling that now. (There is lots of work – lots of work – left to do on the simulation behavior. I want to implements some results code now so that I can make better tests for the behavior.


My approach for this is to create a Results class that will have whatever I want to track. Here's a first draft:

public class Results

{

// FIELDS

public int totalUsers;

public int usersAbandoned;

public int usersExpired;

public int totalUserWaitTime;

public int totalSystemFreeTime;

}

There'll be a bunch more code – methods to collect and process the data.

I added a new Results object to the Simulation fields:


private Results results;

And I added that result object to the calls to the ticks:

foreach (DataUser a in computerQueue) {

a.tick(simTick, results);

}

foreach (Seat b in seats) {

b.tick(results);

Which means that I have to add a result object to the tick methods for those files.

The plan is for the results object to record state changes when the system calls a tick on each object – datauser or seat. Next time, I'll start implementing that record keeping.

The other thing that this change did was to break a number of existing tests. Several of them call tick directly on some objects. Since the method signatures are changed, there's nothing for them to call.

I fixed this by creating wrappers in the test code:


public void tick(int x)

{

tick(x, new Results());

}

…

#if DEBUG

// TESTING CODE

public void tick()

{

tick(new Results());

}

#endif


And that's it for today.


Saturday, August 6, 2011

CQ Simulation: Simulation Tick

More coding today.

I'm working on getting the whole system up and running in some form so I can test and refine it.

The tick method of the Simulation class is the main driver, calling methods in both Seats and DataUser.

So here's today's code:


public void tick()

{

simTick++;

foreach (DataUser a in computerQueue) {

a.tick(simTick);

}

foreach (Seat b in seats) {

b.tick();

}

foreach (Seat c in seats) {

if (c.Free) {

c.currentUser = computerQueue[0];

computerQueue.RemoveAt(0);

}

}

}


I added the last foreach loop today.

I had to change the field currentUser to public, since it was being called from outside. Actually, maybe I should set up a Property for it – but that can wait.

When I ran the tests, it gave me an error:


Exception calling "tick" with "0" argument(s): "Index was out of range. Must be non-negative and less than the size of the collection.


Oh, that test didn't load up the computerQueue with users. The code tried to access the empty list. This needs to be addressed anyway – there could well be situations where there are no users in the queue and the seat needs to go unfilled.

So, next time, I will add a check to the method. I can just use the List Count property.

Wednesday, August 3, 2011

CQ Simulation: Tick Methods

I started out today by adding two more states to a user:


abandon, cutoff,


Abandon means that the user gives up on the line and leaves. Cut off means the user wanted to use a system for longer, but didn't.


Neither of these is affected by the tick method. Once a user has left the line or been kicked off the system, it doesn't matter how much time passes for them.


So, what does the tick method for each of the three methods accomplish?


Here is DataUser.tick:


public void tick (int thisTick)

{

if (thisTick [LESSTHAN] queueUpTime) return;

if (state == State.sitting) { desiredTime--; }

else if (state == State.waiting) { patienceTime--; }

#if DEBUG

if (queueUpTime [LESSTHAN] 0) { throw new Exception(); }

if (patienceTime [LESSTHAN] 0) { throw new Exception(); }

if (desiredTime [LESSTHAN] 0) { throw new Exception(); }

#endif

}


This method is exited immediately if a user is not, yet, in the line.

After that, the desired time and patience time decrease when the user is in the relevant state.


Here's Seat.tick:

public void tick()

{

if (occupied) {

useTime--;

if (useTime [LESSTHAN] 0) useTime = 0;

}

}


If a seat is occupied, its use time is cut by one tick each tick.


Here's Simulation.tick:


public void tick()

{

simTick++;

}


Well, this one needs the most work. How about this:


public void tick()

{

simTick++;

foreach (DataUser a in computerQueue) {

a.tick(simTick);

}

foreach (Seat b in seats) {

b.tick();

}

}


After I caught a typo, this compiled fine. That is, it didn't break any tests.

Still, there aren't any tests that it could hurt much.


Several things have to happen: there needs to be a pass through the seats to see if there are any empty seats and then each empty seat needs to be filled, if possible.


I'm going to start this by adding a field for a current user:



private DataUser currentUser = null;


I want the seat to be able to poll it's individual user to see if the user is done.


If I remove a user from the computer queue list after associating it with the seat, then, later, when I delete it from the seat, it will be ready for garbage collection.


And that will be for tomorrow – I will start working on assigning the user to the seat when the seat is empty.

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.