Ugh. The First of September, already!
I should be happy about this. After all, Autumn is hands-down my favouritest and my best season of the year. Maybe I appreciated it more when the summers were hotter and more miserable. Because this year I barely noticed a summer here at all. I don't even have a concept any more of "summer clothes" - I pretty much wear the same thing all year long. Not that I'm complaining. I'm really not. I don't miss that hot and humid miserable summer weather I knew so well in Ohio and Massachusetts. But it does take away some of the pleasure of cooler weather when it wasn't so hot to begin with. At least this year I already know where to head to get fresh pumpkins.
I'm still reading ,em>The Pragmatic Programmer in tiny bites. The more I get into it, the more I find that it's written for a more experienced audience. They mostly focus on the philosophy of how to best program, but they throw out concrete examples in the way of code in languages I haven't seen yet. So for now I'm taking what I can from it (which I still think is a useful amount), knowing it will probably benefit me to read it all again in a few years. (Assuming someone has foolishly hired me by that point.)
Tip #35: Finish what you start.
How to Balance Resources
- The "finish what you start" tip tells us that, ideally, the routine that allocates a resoure should also free (close) it.
- Nest Allocations
- Deallocate resources in the opposite order you allocate them. That way you won't orphan resources if one resource contains references to another.
- When allocating te same set of resources in different places in your code, always allocate them in the same order. This will reduce the possibility of deadlock.
- Balancing resources in object-oriented languages
- Encapsulate resources in classes
- Use of NodeResource and auto_ptr in C++
- Use of Finally in java
When You Can't Balance Resources
There are times when basic resource allocation pattern isn't appropriate. Commonly this is found in programs that use dynamic data structures. One routine will allocate an area of memory and link it into some larger structure, where it may stay for some time. The trick here is to establish a semantic invariant for memory allocation. Who is responsible and what happens when you deallocate the top-level structure?
- Top Level Structure (TLS) is also responsible for freeing any substructures it contains, and to recursively delete data they contain.
- TLS is simply deallocated. Any structures that it pointed to (and not referenced elsewhere) are orphans.
- TLS refuses to deallocate itself if it contains substructures.
Checking the Balance
Build code that actually checks that resources are indeed freed appropriately. Produce wrappers to keep track of all allocation & deallocations of each type of resource.