A Curmudgeon in Redmond

Using and abusing software since 1966

Cleaning Up After Your Program

You've got a big, complicated computer program and it's time for that program to exit. The user just chose the Exit menu, or he clicked on the close button of his main window, or your service has been asked to stop. What do you do? In my experience, people writing termination code fall into two major camps:

Cleanliness Is Next To Godliness

People is this camp will write lots of code to close all of their windows, ask their threads to stop, release all of their COM objects, release all of their memory, uninitialize COM and WinSock, and so forth. They'll spend a lot of time in design and debugging, ensuring that things get torn down in the right order, so that nobody depends on a module that has already been finalized.

The good news is that these people get the benefit of leak-finding tools. In theory, when their process stops, it's in exactly the same state as when it started. Any differences constitute a leak.

A Smith and Wesson Beats Four Aces

People in this camp take a different approach. They know that the OS will clean up properly when a process dies, so they just call TerminateProcess. Their termination code works first time, every time.

In a few cases, they'll introduce code during termination to send courtesy notifications to other parties, letting them know that they're dying. Presumably, these other parties would work properly without the notification, but the notification saves these parties waiting for a timeout period.

Overall, I find myself more and more drawn to the second model, mostly because code that you don't write seldom has bugs. What are your preferences?

Posted: Aug 22 2008, 12:20 PM by jim | with 2 comment(s)
Filed under:

Comments

Erik said:

The second model is good until the day you decide that your program is going to be part of a larger program and it will only be a thread in another program... At that point you won't be able to afford any leaks anymore...

# August 23, 2008 11:55 PM

jim said:

Erik,

It sounds like the day you decide to do that is a good day to write the cleanup code. Let your motto be "We will write no code before it's time."

# August 24, 2008 11:36 AM