Daily Archives: March 2, 2006

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.