Object design in C# using the PowerShell IDE as a development and testing environment.
Saturday, December 17, 2011
Backups
Saturday, December 10, 2011
Some setup
I've created a new directory and created a new script file for my finances functions.
Back in my profile, I made a little function that will change to the new directory:
function do-finances {
cd MyDir
$a = (Get-Host).UI.RawUI
$a.ForegroundColor = "blue"
$a.BackgroundColor = "white"
clear
}
set-alias df do-finances
So, if I type "df", I'm moved to the right directory - and that other stuff? Well, if I'm actually going to try this as a place where I keep my account information, it would be nice to know, for sure, that I'm using PS for something different than I usually do.
And it gives me another option.
I can add the following lines to the new-transaction function from a couple of days ago:
$a = (Get-Host).UI.RawUI
$a.ForegroundColor = "magenta"
Which means that every time I have unsaved data - the transaction just created - the shell will have a different appearance.
Next time, persisting data.
Thursday, December 8, 2011
A Pilot Project
- It assumes $total will be blank.
- It assumes that the amount in the first entry of $checkbook will be a negative number.
Wednesday, December 7, 2011
Everything we need is here
I don't mind spreadsheet programs, but there is a lot of mousing around - and I wonder if that's all that necessary. Then it occurred to me that PowerShell has the kinds of data types necessary to keep track of this without adding anything fundamental.
So, I'll see what something like that would look like.
We need a record. That is, every transaction needs to have a certain amount type of information. A hash table stores key value pairs. How about this:
PowerShell: $a = {month=0;day=0;payee=blank;amount=0;category=blank;year=0000}
PowerShell: $a
month=0;day=0;payee=blank;amount=0;category=blank;year=0000
Some design decisions:
Why month and day instead of a date object? Seems like overkill. I guess I can implement it with date objects later.
Why is the year last? I plan on using default values, so that will only have to be set once per year.
So, let's make a function out of this:
PowerShell: function new-transaction ($month = 0, $day=0, $payee="blank", $amount=0, $cat="blank", $year=2011)
>> {
>> @{month=$month;day=$day;payee=$payee;amount=$amount;cat=$cat;year=$year}
>> }
>>
And how does it work?
PowerShell: $a = new-transaction
PowerShell: $a
Name Value
---- -----
year 2011
payee blank
amount 0
cat blank
month 0
day 0
PowerShell: $a = new-transaction 12 8 test 4.35 groceries
PowerShell: $a
Name Value
---- -----
year 2011
payee test
amount 4.35
cat groceries
month 12
day 8
And now this needs to live in a script file - my profile, for now.
Here's what I put in:
function new-transaction ($month = 0, $day=0, $payee="blank", $amount=0, $cat="blank", $year=2011)
{
<#
.SYNOPSIS
Create a new transaction hash table.
.DESCRIPTION
Creates a new hash table with vaues for required parameters. Default values are
provided.
.PARAMETER month
Month from 1-12. No verification
.PARAMETER day
Day from 1-31. No verification.
.PARAMETER payee
Payee string.
.PARAMETER amount
Amount.
.PARAMETER cat
Spending category.
.PARAMETER year
Year.
#>
@{month=$month;day=$day;payee=$payee;amount=$amount;cat=$cat;year=$year}
}
set-alias nt new-transaction
Yes, I wrote help for my function - you should, too.
Here's what the output looks like:
PowerShell: nt
Name Value
---- -----
year 2011
payee blank
amount 0
cat blank
month 0
day 0
PowerShell: get-help nt
NAME
new-transaction
SYNOPSIS
Create a new transaction hash table.
SYNTAX
new-transaction [[-month] Object>] [[-day] Object>] [[-payee]
Object>] [[-amount] Object>] [[-cat] Object>] [[
-year] Object>] [
DESCRIPTION
Creates a new hash table with vaues for required parameters. Default values are provided.
RELATED LINKS
REMARKS
To see the examples, type: "get-help new-transaction -examples".
For more information, type: "get-help new-transaction -detailed".
For technical information, type: "get-help new-transaction -full".
PowerShell:
Next up: Put the transaction records into an array.
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.