Code Sample: Wrapping Some Microsoft® Windows® API Functions

Introduction

The Microsoft Windows API offers a ripe and well-known source of examples of a confusing and brittle interface begging to be refactored. Since the API is published it cannot actually be refactored, but wrappers can be built around it to overcome some of the problems presented by the API and to better organize the facilities exposed by the API. The most well known wrapper of the Windows API is MFC. Unfortunately, MFC retains many of the problems of the API as well as introducing a few new problems, such as excessive coupling and vendor lock-in.

In this example we will start with some fairly conventional C++ code to display the content of a text file using Windows API functions. We will then progress through several incremental stages as we we discover and implement improvements. Our goal is to create reusable classes that implement functionality needed to support the C++ program.

One of the design criteria for these classes is that they are not coupled to the original program: they can be used elsewhere without modification. There will also be minimal coupling among these reusable classes: when there are interdependencies they are necessary and known. Not only does such a design enhance reusability, it also facilitates testing. We define the expected behavior of each class and devise tests of that behavior. Just as we can reuse these classes in different contexts we can also test in one context and expect the same results in a different context.

As we progress, complexity will move out of our original function. More and more of the knowledge of how to interact with the Windows API functions will move into the reusable classes. Errors will be handled automatically. We will move toward a function that resembles an outline of what is to be done, rather than one dominated by details.

[Previous] [Next: The base code]


Microsoft and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

The Code Untangler home page

Copyright © 2001, Randy McLaughlin