Uli's Web Site
Hungarian Notation good, Exceptions bad?
Joel Spolsky wrote a nice article about the merits of Hungarian Notation and the downsides of Exceptions. While I mostly agree, His solution is only the first step along the path. The solution is not to use Apps Hungarian from now on and to abolish Exceptions. The solution is to fix these problems in the languages.
For example, Apps Hungarian fixes a problem with the data type hierarchy in most programming languages. We need a way to say: You can't turn a value of type XCoordinate into a value of type YCoordinate even though they are both subtypes of ints. Once we have that, we don't have to manually read prefixes, we can let the computer check our types. It's the very same problem the introduction of typed parameters to C solved ages ago.
Similarly, there are ways to solve the problem with skipping code that needs to run even when an exception is thrown. C++ attempts this through having stack objects whose constructor and destructor perform allocation/cleanup of resources. Stack objects are destructed even when an exception is thrown. Objective C has autorelease pools that can be used to similar effect.
Of course, this requires you to design differently. Instead of (C++-like pseudocode):
char* foo = malloc(50)maypossiblythrow( foo )free( foo )foo = NULLyou need to write:
auto_ptr<char> foo = malloc(50)maypossiblythrow( foo )I'm not saying this is the best solution, but it is one, and it is also fairly easy to spot. Not to mention it's less lines of code, which typically endears any solution to us lazy programmers.
But Joel probably didn't mention this because he already saw the flaws: It's easy to overlook one of these balanced cases and just forget to write a class to handle it on construction/destruction. And there are cases where we only want our object disposed on exceptions, but on success one of the skipped functions will take over ownership of the memory. It's easy to miss those and leak an object, or overcompensate and get a zombie. Garbage collectors could be used to solve this, but they're not a good fit for all platforms (e.g. some embedded and realtime systems). Sometimes you just have to compromise, and then Joel's suggestion to just drop exceptions as well is a good idea.
As always, it boils down to knowing both the advantages and the disadvantages of each tool you're using, and to choose based on your current project, not based on personal preferences. This includes undesired interactions, and knowing that separates a programmer from someone who has learned a programming language.
Created: 2005-05-14 @886 Last change: 2005-05-14 @905 | Home | Admin | Edit|
© Copyright 2003-2017 by M. Uli Kusterer, all rights reserved.