QualityCode.com Essay: Code Sandwiches

When you are designing your code (assuming you do at least a little function-level design before you dive in), always think about the sandwiches you will be building.

What is a code sandwich? It’s the idea that on both sides of the real work (the “meat”) you often have initialization and cleanup code (the “bread”). As with a sandwich, if you forget either piece of bread, it can get messy!

Some examples of sandwiches are: Opening and closing a file. Allocating and freeing memory. Creating and destroying an object.

Pretty basic, right? Sure. And with an OO language like C++, you can even use an object with local scope that performs the cleanup automatically. Strings are a perfect example in C++: You can have a local string variable that frees its own memory when it goes out of scope at the end of the function.

But there’s more to the story. Any time you start a sandwich, make sure you know exactly where the closing piece of bread will be. If it’s within the same function, that’s great. But that’s not always possible or desirable. So you need to think carefully about how this sandwich is eventually going to be closed.

If the sandwich is started in a function like open, it is natural to expect that you will have a corresponding close function that will finish it. If the sandwich is started when an object is created or initialized, it should be finished when the object is destroyed. Strive for symmetry between where your sandwiches are started and finished.

Also think about error handling. This can be tricky even when the sandwich exists completely within a single function. Make sure that the sandwich is always finished if it is started. Also make sure that the sandwich is not finished if it wasn’t started. Check every code path to make sure everything is in order.

In Java, you can use an empty try/finally to ensure the cleanup happens, even if an exception is thrown.

There are certainly many more aspects to sandwiches, but I hope I’ve given you some “food for thought”.

This was originally written in 2001, with minor updates in 2017