Wishing for a destructor (C#)

 

I like the C# programming language. It feels like C++ done right, divesting itself of much of the C legacy that complicates matters so much. When I do programming, I prefer to use this language. Having to go back and deal with C++ just doesn’t give me that warm feeling like it used to.

But, I have a pet peeve that I miss from C++.

Choose… Choose the form of the Destructor!

Quick recap. Here’s a brief C++ function…

 void MyFunction()
{
string x;
MyOtherFunction(x); /* Pass by value. */
}

Doesn’t look like much is going on, but there’s five function calls in there.

  1. A constructor function is called to build x.
  2. A copy constructor function is called to copy x for the function call.
  3. ‘MyOtherFunction’ is called.
  4. A destructor function is called to tidy up the copy of x.
  5. The same destructor function is called to tidy up x itself.

The clever bit is that the compiler has worked out when objects go “out of scope” and inserted calls to that’s objects destructor function in exactly the right place. Even “anonymous” objects are tidied up. Say a function is called that returns an object, but the caller just ignores the return value. The compiler spots it and inserts the destructor call in just the right place.

C# doesn’t do this. Instead, from the very beginning of the language, unused objects are “garbage collected”. Every so often, some code will run that goes over everything built by the program and sees if its being used anywhere. Anything that can’t be traced to running code is removed. Doing it this way allows the programmer to share objects between two different areas of code, without having to worry about which one has responsibility for tidying up.

I imagine that when the very clever people at Microsoft designed the C# language, they had already decided to use garbage collection, and so concluded that this messing about with destructors was no longer needed. No need to insert a function call into code, just leave the object lying around and the garbage collector will deal with it.

This would all great if memory was the only resource we have to keep track of. Open file handlers, database connections, etc. All must closed in a deterministic manner, instead of at some unknown time in the future when memory is about to run out.

Microsoft didn’t leave us completely out on the branch, classes that need to be tidied up can be written to implement the IDisposable interface. This allows the using block to work.

 using (SqlConnection con = new SqlConnection(db))
{
/* Use con. */
} /* Dispose con. */

With the using block, just like with the C++ destructors shown above, the compiler inserts a call to the tidy-up function at the end of the block. Even if there’s a return or throw statement in the middle, it’ll make sure everything is tidied up when the code leaves the using block.

But why have the using block at all? If you forget to include the using block, the tidy-up code won’t be called (unless you invoke it manually) and you won’t even get a compiler warning. (You don’t get the warning for very good reasons which I won’t go into right now.)

Even when you use using correctly, adding a using block to a function means introducing an additional block, with all the block-visibility issues and additional indenting that implies.

Structs to the rescue

Fortunately, C# and .NET come with a type of object called structs. These are similar to classes except they are solid value types rather than references to data floating in the ether. The practical difference is that when a struct value is copied (such as when passed into a function as a parameter) and you change the value of the one of the copies, the other copy stays the same.

In contrast, when you copy a class value, you’re instead just making a copy of the reference, so both point to same data. Change the contents of one, and the other changes value too, because there is no “other”.

So what if, when a struct appears in code, it came with an automatic using block attached? That way, we could open files or database connections just by introducing one in code and it would be tidied up in a deterministic way.

To complete the job, we would need mechanisms to support copy constructors and assignment as well as the final destructor call, just like the C++ people are used to.

I’ve been nursing this peeve and whining about it for so long that I’m even boring myself. I plan this to be my last word on the topic and in future I’ll just post links to this article. Enjoy.

Picture credits
“staypuft_3feb2009_0621” by patrick h. lauke on flickr
“choose determinism” by alyceobvious on flickr
“John E. Cox Memorial Bridge” by Elizabeth Thomsen on flickr

Paying for Power

Being an evil genius, I’m obsessed with getting as much power as possible. If only I could get power for nothing, but alas, I have to pay for it.

In England, and most of the western world, we have a well established system of sending electricity from the power stations to me and sending money in the opposite direction. It works, but I think we can improve on it.

An Electron’s Journey

Electricity starts life at the power stations. They sell their power supply on the grid at market rates, competing with other power stations. The price of electricity fluctuates over the day. If the price goes down far enough, they might switch off the generators, keeping their raw materials for when the price goes up. A wind farm can’t keep stocks of wind in reserve, so they will stay online all the time regardless of the price.

We, the public, never see those fluctuations in price. Instead, we purchase electricity from a supplier who deal with the power stations. The suppliers usually charge us a fixed amount per unit of energy, sometimes having a daytime rate and an overnight rate, but the price they charge us is fairly stable, only changing the rates every few months.

(As well as the suppliers, we also pay the companies that maintain the grid system and meters in our homes. This article is not about them.)

When all is said and done, what do the suppliers actually do? They don’t generate the electricity and they don’t bring it to us. They are middle-men who flatten out the price, charging a bit more than the expected average price, like an insurance premium, to compensate for the risk of over-demand and price rises. Do we need that service? We have insurance to spread the risk of unexpected events, not for the everyday costs of life.

What if, instead, we had a minimal supplier that just handles the accountancy at a low cost, quoting a price that changes every five minutes, tracking the wholesale price. (Perhaps having an easy to use gizmo that displays the current price.) With this type of supplier, we would probably save money over the long term. After all, we wouldn’t be paying that insurance premium any more.

But more important than that, it would give us an interest in when we use electricity. At the moment, we really don’t care that the price of electricity rises dramatically during the adverts on popular TV shows. We all switch on our kettles at the same time, not really caring about the economics. If we felt the rise in price, we might plan our tea making better to avoid these peaks and save some money.

This plan wouldn’t have worked when the grid was originally built, but computer and communications technology have advanced to point where we can finally think about pulling down the old ways of working. I’m looking forward to it.

Picture credits.
Nuclear power by koert michiels on flickr.
insurance prohibits ladders by stallio on flickr.

The Making of an Evil Genius

When I was around 9 or 10 years old, my school, as they would every year, put on a Christmas show. The younger children would re-enact the birth of Jesus of Nazareth and then the older children would perform a play. That year, we were performing Grimm’s Snow White.

I wasn’t performing on stage though. Instead, I was in charge of the music. We had a cassette of all the music and the children on stage would sing along. I would press play when its time to sing and after, position the cassette for the next song.

I wouldn’t know it at the time, but it would be this rather mundane task that taught me one of the most important lessons of my life.

A “technical hitch”

The music cassette had all the tunes with large gaps between each song. The cassette player was an early 1980s era device with a mechanical counter and a button to move all the dials back to zero. The number on the counter weren’t anything useful like seconds but how many times the motor had turned, or something like that. Fortunately for me, the teacher organising the play had gone to the trouble of writing down the counter position for each song and the order in which they are to be performed. What could go wrong?

Indeed, what could go wrong? A few days or so before the big performance,  we did a dress rehearsal and I demonstrated I could operate a cassette player without assistance. Everyone was happy.

Finally came the day of the show. Before the audience had arrived, the teacher told me to position the cassette for the first song and I did that exactly. Everything was ready. During the show, the first tune was played without a hitch and after the song was over, I dutifully positioned the cassette for the next song.

Time for the second song… disaster!

I had pressed play but instead of music, silence. I could hear the children on stage singing “We dig-dig-dig-dig-dig-dig-dig in a mine…” until they realised there was no music. The teacher duck her head behind the curtain and asked what was happening. I showed her the tape was running and I didn’t know what was wrong. She had to go up on stage and apologise for the “technical hitch”, to much laughter from the audience.

Truth is, I knew exactly what went wrong and I was already fixing it. What happened, was that when the younger children did their nativity play, their teacher was using the same cassette player for their music. When they finished, they put our cassette back in the player but the counter was all messed up. My first song was fine because the tape was already in place, but when I positioned the cassette for the second song, it was based on a counter that was in the wrong place. I had been playing one of the gaps between songs.

What’s more, I remember thinking that exactly this would happen while watching the earlier nativity play. I was sitting there thinking “I hope they put tape counter back when they finish.” But I said nothing, after all, the teachers were in control and they would have thought of this too and wouldn’t want me bothering them. I mean, they’re adults!

While I was rather mocked by the other children for spoiling an otherwise perfect performance, it turned out to be one of the most important moments of my childhood. It taught me possibly the most valuable lesson I’ve ever had.

People in authority can be wrong.

After that incident, I started looking at adults in a new light. Not just teachers, but my parents, politicians, bishops, experts, celebrities, anyone in authority. I finally saw them as the human beings we all are.

Picture credits:
“Samantha’s Christmas nativity play” by alecea on flickr.
“Soundesign tape deck” by kumar303 on flickr.
“Silence */” by circo de invierno on flickr.

is, then as (C#)

The C# language has a pair of related operators, is and as. Say you have an object, x, and you want to know if its really type Form underneath.

(x is Form) will be true if it is, or false if it isn’t. The as operator will actually perform the conversion, returning null if it can’t be converted to that type.

One common piece of advice to C# programmers is to avoid using the is operator. Here’s how both of these operators are typically used together.

    if (x is Form)
{
Form frm = x as Form;
/* Use frm. */
}

While the code works, all the is operator is doing is performing an as operation, and checking if the result is null or not. In other words, (x is Form) is equivalent to (x as Form != null). This means the code above is really saying…

    if (x as Form != null)
{
Form frm = x as Form;
/* Use frm. */
}

See that. The same as operation was done twice. What a waste! So, the standard advice is to re-write the code to use just one as operation.

    Form frm = x as Form;
if (frm != null)
{    
/* Use frm. */
}

Simple. So what’s the point of this article? Why use is at all?

The problem for me is that is just looks so darn nice. Beginners very quickly understand what’s going on when they see it. The re-written code that checks for null just doesn’t look as pretty and isn’t as obvious what’s going on.

You may be wondering what the cost of this additional operation is. I knocked together a quick test which looped is-then-as and then looped the optimized version the same number of times and reported the difference in time. When I increased the count to 100,000,000, I saw approx one second difference build up. That’s a lot of looping.

But hey, that cost is non-zero, and I’m wondering why. Compilers are pretty good these days. I recall advice from long ago that its better to use an XOR operation to check if two values are equal, or to use shift operations instead of multiplying. These days, best practice to write what you mean and leave micro-optimizations to the compiler. So why doesn’t Microsoft’s C# compiler optimize is-then-as into a single operation?

I don’t know. It could be that its not worth the development team’s time, or maybe there’s a subtle reason that escapes me right now. I wish I knew. But if we could eliminate the repeated operation and use is freely, code would be lot nicer to look at.

Picture credit: Fruit balance by Pickersgill Reef.
Many thanks to Eric Lippert and the commentators to his article that inspired this piece.
Update 18/Jan/2010: Introduction modified to be better understood by non C# programmers. (Thanks Andrew.)

Computers are fast!

Killer Sudoku is a popular variant on the perennial Sudoku game found in British newspapers. The same rules about the numbers 1 to 9 appearing only once in row, column and 3×3 box still apply, but unlike Sudoku, the puzzle doesn’t come with any numbers filled in. Instead, cells are groups with dotted lines and the total of all those cells are written in.

Here’s part of a puzzle. The two cells grouped by a 10 could be 1+9, 2+8, 3+7 or 4+6. (It can’t be 5+5 because that would mean two 5s in same box.) Not a lot to work on, but also look at the three cells grouped by a 23 in the same 3×3 box; The only possible fit is 6+8+9. This means the only possible fit for the 10 group is 3+7, as all the possibilities would clash with the 6,8 or 9 required to make the 23.

I could go on. If you want to complete the puzzle, its the Guardian‘s puzzle number 166. The point of this article isn’t to solve the puzzle, but something I observed along the way.

Am I sure there’s no other way to split 23 into three parts, 1 to 9, without duplicates? I confess, mental arithmetic is not my forte. Part of the puzzle solving process for me is going through each dotted group and building a crib sheet on all the possible ways to make the total, so I can cross them off later.

This isn’t a part of the puzzle I particularly enjoy, so I decided to automate it. (Is that cheating? I don’t think so in my circumstances, but that’s another topic of conversation.)

So I sat down and designed an algorithm…

  • Input: n (the number of cells, 2 to 9) and m (the total, 3 to 45).
  • Output: All solutions to SUM(n integers 1-9 without duplicates) = m.

Only problem, as with so many mathematical endeavors, life got in the way. By the time I had worked out a basic algorithm, I noticed it was 2AM and suddenly felt rather tired, but I didn’t want to stop, so I simplified my plan.

Loop, starting with (1,1,1,1,1,1) then (1,1,1,1,1,2), ending with (9,9,9,9,9,9). For each combination, if they add up to the target, have no duplicates, and is in order, add it to the list. It was a very inefficient algorithm, but it would work and I wouldn’t have to expend much thought on building it.

Then something surprising happened. While testing with 2 or 3 digit targets, it was near instantly fast, but I had expected 6 digit targets to take something like a few minutes. In fact, it took 2 seconds.

2 seconds!!!!! I had learnt to write programs on my early 80s BBC Micro and I was used to leaving it running overnight calculating something like this. Computers are fast!

(If all that seems too much like hard work. Wikipedia have built the tables for you.)

About This Blog

Jawohl! I am Wilhelm von Hackensplat, software developer and evil genius. This is my blog.

I’ll be writing on software development, otherwise known as that-which-pays-the-bills. I’ve been doing this for most of my life, ever since mother Hackensplat bought a Sinclair ZX81 all those years ago.

I have tried blogging before, but I found myself really dissatisfied with the structure of a blog, specifically the normal view of showing the most recent posts first. To me, that’s not the most important thing. I want a casual visitor to bask in my unaccountable brilliance and see my best stuff.

This is my main beef with blogging software, that it doesn’t make for a very good document publishing system. There is a layout for blogs, and thou shalt not deviate from the norm. What I’d like is a document management system that includes a capable blogging sub-system. I would write my own perfect system, but time is short and life is hard. So back to blogging, here I am.

GenieƟen!


Picture credits:
Laboratory by tk-link of flickr