The Coding Monkey

Thursday, June 02, 2005

In Defense of Hungarian Notation

Joel on Software has an excellent article defending Hungarian Notation, which I highly recommend. It's an excellent article which gives examples of how Hungarian is still useful today. I'm a firm believer in Hungarian Notation, and still use it to this day (properly I might add) despite the evil looks from coworkers. The problem with Hungarian was that it was bastardized over the years. When it was originally invented by Charles Simonyi at the Microsoft Apps team (think Word and Excel), it was used to differentiate variables of the same type, that had radically different meanings. For instance, two variables might represent coordinates with DWORDs, but one might be relative to the screen, and one might be relative to the page. Assigning directly between the two would cause an error, but would be syntactically correct:

DWORD xwCell;   // Cell location relative to Window
DWORD xlCell;   // Cell location relative to Layout

// ... Later on

xwCell = xlCell;             // Logic Error
xwCell = XwFromXl(xlCell);   // This is Ok, we converted.

Somehow (and Joel explains this), Hungarian got bastardized so that the prefix was only used to denote the variables physical type. So you would get code that looked like this instead:

DWORD dwCell;    // Cell location relative to Window
DWORD dwCell2;   // Cell location relative to Layout

// ... Later on ... imagine a couple screens away

dwCell = dwCell2;   // Logic Error... but would you know it?

As you can see... the Hungarian that eventually took hold has much less utility. Sure it's nice to know that a variable is a DWORD, but that doesn't prevent the logic error. Maybe it's the fact that I'm a huge fan of code reviews that makes me like Hungarian. I actually print out code and go over it with a pen and highlighter. I write notes, I ask questions... and having conventions that make these errors pop out at you help more than you can know.

0 Comments:

Post a Comment

<< Home