Creating an Object-Oriented Framework from an existing API

One of my personal goals this year is to go through Petzold’s book on Programming Windows. During that 1500+ page journey I’m creating a framework class library for my personal use while developing Windows applications. This way I can simultaneously learn the intricacies of Win32 while at the same time developing a framework library that is different than MFC or .Net. Why would I want to do that? Well… MFC isn’t exactly lightweight and it has some performance issues. But aside from that, it’s just fun!

When embarking on something ambitious like this, however, you immediately comes across issues you need to solve, such as how to map an essentially flat API like Win32 into an object-oriented hierarchy of reusable classes. Win32 was, after all, designed before object oriented programming became popular.

There are some patterns that you can use to recognize opportunities for classes and inheritance.

1) Some parameters show up a lot, often as the first argument to a function. All of the GDI functions, for example, take a handle to a device context. This pattern is much like the implicit this parameter in OO programming. A device context is a good candidate for being wrapped into a class, with the GDI functions as members. Most window manipulation functions take as an argument a handle in the form of HWND. Window is another candidate for a class. There are other examples, but these two are good starting places for creating the class hierarchy.

2) There are many variables that are often typecast to other types. Think GDI handles such as HPEN, HBRUSH, and HBITMAP. GDI functions such as SelectObject return a generic HGDIOBJECT which is usually cast to the appropriate HPEN or what-have-you. Fundamentally, these are all the same basic data type–just interpreted differently. This situation is a good candidate for inheritance and polymorphism.

You can also look at other framework libraries for ideas, but this idea is not as attractive, because the point is to develop something original through the learning process, and if those frameworks provided exactly what you wanted, why bother creating a new one anyway? On the other hand, much can be learned by examining proven techniques.

Another big issue you need to deal with in developing a framework library is messaging, but I’ll deal with that in a later post.

ArgumentNullException and ArgumentException

Does it strike anyone else as ironic that ArgumentException and ArgumentNullException have mismatched argument ordering? The parameter name is first for the null version, but second for the other one. Uggh… this makes it awkward to remember if you use both. ArgumentOutOfRangeException follows the example of ArgumentNullException.

I can see no obvious reason for the discrepancy. In all three cases, the constructors are exactly the same. In fact, MSDN explicitly says that the behavior is the same.

SM_SECURE

In the system metrics that you can retrieve with GetSystemMetrics, one of the available options is SM_SECURE.

The only explanation provided is “Nonzero if security is present; otherwise, 0.” What does that mean? On my computer, the value is 0. There are a few different ways security can be “present” in my mind–what specifically are they talking about here?

Google, MSN, MSDN yield no useful information.

A Debugging Exercise

A few weeks ago I had an interesting debugging problem. A program we develop had a memory leak in it that Visual Studio was catching when it ended. The trace text was something like this:

Detected memory leaks!
Dumping objects ->
{292300} normal block at 0x05590040, 2771928 bytes long.
Data: <> FF FF FF 00 FF FF FF 00 FF FF FF 00 FF FF FF 00
{292294} normal block at 0x05110040, 2613312 bytes long.
Data: <> FF FF FF 00 FF FF FF 00 FF FF FF 00 FF FF FF 00

Visual Studio 2003 is often pretty good at telling you where a memory leak occured, giving you a source code file and line number of where the memory allocation originated. In the case above, I don’t have that. There are two relatively easy ways of solving this.

The first method is to examine the data that isn’t being freed. In this case, I have two large objects of about 2.5 MB each. That’s pretty big–there aren’t too many (if any) individual objects in the software that are that large. So it could be an array. The data begins with a repeated pattern {FF FF FF 00}. Definitely looks like an array of 4-byte segments. Applying a little knowledge of the application itself–it displays large bitmaps–and we realize that the memory comes from an array of RGB values.

Another way to investigate this is to set a breakpoint on the memory allocation that isn’t being freed. The number in braces {292300} is the memory allocation number in debug mode in Visual C++. In order for this technique to work, you must first ensure that the number is the same each time. In my case, the memory leak would happen if I just opened and closed the program (because an image is always being drawn) without doing anything else.

First, set a breakpoint at the beginning of the program (or any place definitely before the memory leak). Start the program and when it breaks, enter the following into the watch window:

{,,msvcr71d.dll}_crtBreakAlloc

And for the value enter 292300.

If you continue the execution, the program will break on the 292,300th memory allocation. It will stop in the memory allocator, and you can then look at your stack frame and see exactly where the memory allocation is taking place.

MSDN has a great article about this.

In my problem it was for a set of memory blocks being used as working space for resizing and smoothing bitmaps. They were allocated once during execution and thus did not really provide a long-term threat. This leads to a possible third solution:

Ignore. All memory is reclaimed once the program exits. Nobody would ever do that, though…. would they?

…of course not…

Dilbert and Unfit by the same artist

I haven’t seen this anywhere else on the web yet, but my suspicion is starting to grow. Even if it’s a nutty theory, I’m still going to put it forward. Has anyone else wondered if Mike Belkin and Scott Adams are the same person?

There is a relatively new comic out there called Unfit by author Mike Belkin. Recently, Dilbert’s Scott Adams hosted a contest for a new artist for Unfit on his blog.

Has it occured to anyone else that the type of humor portrayed in both comics is similar? I think there is even a strong similarity in the artwork (hence the reason for an artist contest?) and the lettering. Unfit is just slanted differently.

Does anyone else think this?

Credibility

One thing I cannot stand that is so prevalent in the computer industry is criticism by people of ideas, products, and technologies that they don’t understand. You see this a lot in the OS wars–especially of Windows, but Linux and Apple are not immune.

In very few cases do people have a well-reasoned and thought out explanation for their feelings. People who bash other ideas for their “religious” reasons are not intelligent–they are freaks who should not be trusted to make good decisions about technology.

Sure, there are horribly bad products out there, but those are mostly ignored and quickly die off. Religious wars start over successful products. A little study and research into the reasons for various design decisions would go a lot towards increasing the intelligence of most of these people.

Why Developer Certification Doesn’t Make Sense

Much as been said about the pros and cons of requiring software engineers to be certified, just like the medical, law, and engineering fields.

I personally do not believe this should happen. First of all, those other, certified, fields have existed for thousands of years. Computer Science is not even a century old. The field is incredibly immature. Sure, we have fancier tools, and we can do some amazing things, but we’re still in infancy!

Look at the best software makers you can think of. I won’t name names. Think of the highest quality applications you have ever used. Now think of all the problems and bugs and limitations of that software. If that’s the best we can do, what meaning does certification have?

All the other certified fields have well-established standards that have withstood the tests of time. Computer Science hasn’t had the time. We can’t even agree on the best way to make software!

So go ahead and enforce certification now, but it’s not going to mean anything.

Golden Days

Yesterday was a golden day. Everything I touched turned to gold. I solved all the problems that came up, fixed bugs right and left, and even figured out the root cause of a bug that’s been plaguing us for a month or so.

Some days are like that. I like days like this, because I feel like I’m on top of the world and that on the one hand, I’m not getting paid enough, but on the other it’s so fun I’d do it for free! (if any of my bosses are reading this, concentrate on the first part of that! 😉

Today was merely a silver day. Thankfully, nothing went wrong, and I did quite a bit of good stuff. Not quite golden. Maybe I should have a calendar and put gold and silver stars on the days. That’s probably a bit much. But I could have rust-covered frown-faces for those unspeakable days.

Infinite Enjoyment with Finite Resources

Have you ever thought about the miracle of music? OK, some might object to the world miracle, but I’m talking about music, something where transcendental terminology is appropriate.

On a piano you have 88 keys. Instruments can go higher (violin) or lower (organ), but with the same repeated 12-note octave everything in western music is created.

Thing about that. 12 notes, repeated over and over, at higher and lower frequencies. It’s such a small working set! How many melodies can you create in one octave?

More importantly, how many beautiful melodies can you create? Thousands of composers over thousands of years have proven that there is no limit to the originality possible with these limited tools. Of course, there are accompanying tools: instruments, rhythm, and personal style. But always with the same 12 notes.

And an infinity of beauty is possible because of it. Granted, our notions of what art is beautiful change over time, but who denies the beauty of War and Peace, Les Misérables, The Last Supper, Intermezzo from Cavelleria Rusticana, Jesu, Joy of Man’s Desiring, Pachelbel’s Canon in D, or anything by Rembrandt? Beauty grows, never shrinks.

Now imagine if there were infinite numbers of keys–how would that change things? What if we doubled the resolution of the notion of half-step (F toF#, for example) to a quarter step?* 8th step? 16th step? I don’t think this will inspire more creativity (at least not creativity that produces beautiful works of art). Too many options will spoil the landscape–clutter it up so much that not only can we not understand music produced like this, but creating it becomes onerous–there are way too many possibilities. The mathematical framework of music forces us to contain our creativity within bounds of structure that “make sense” to our minds, that allow us to understand, dissect, and enjoy.

The modern notion that lack of constraints promotes creativity is a false one. No constraints means less thought and feeling has to be put into work.

I hand you a canvas and tell you to paint your best work ever. What will you do?

You might ask–“What is the subject of the painting?” I respond–“Anything.”

You can’t work like that. Of course, you might come up with a theme yourself, but now you’re constraining yourself along a certain path.

Another example: in the 20’s Hollywood had no movie-making constraints. There were no censors. Do you remember many movies from the 20’s? In the 30’s, constraints were imposed by the government, forcing Hollywood to clean up its act. How many movies are memorable from the 30’s onward? A lot, even to my young mind. I think a case could be made that dissapearing constraints now is creating the same dull period in Hollywood that existed back in the 20’s. Sure, you can make anything you want, but who is actually going to care deeply about it?

Software development thrives under these conditions. Software developed with no or few constraints quickly looks like garbage and is much less useful. Impose coding constraints, design constraints, interface constraints–all these RULES you have to obey–and your code will become artful. Look in all the books on the subject of turning average programming into craftsmen, artists, what-you-will–the books mostly teach you RULES to follow, lines to stay within.

Coloring outside the lines is fun every so often, but you rarely frame it and call it art.

* Of course, continuous instruments such as strings can do this, but it’s not standard musical technique.