Hungarian Notation

In which I pontificate on the subject of Hungarian Notation


Hungarian Notation is a contentious topic

It boils down to an ambiguity for the word “type” within English / C++. MicroSfot’s modern style-guide says not to use “Abbreviations and Acronyms” or “Hungarian Notation” - originally Hungarian Notation was a style of abbreviation. I’m going to paraphrase a long blog post by Joel on Software and summarize my thoughts at the end.

Story-Time!

C-family languages (C/C++, Java. C# JavaScript, Python, etc) have rather “weak” types, things like Haskell and Ada95 have strong types. If you define an integer in Ada95 (for example) you can give it a range of values (1 to 7) or even names (days of the week) to prevent confusion. So you’ll never be able to assign a day-of-the-month (1 to 31) value to a day-of-the-week (1 to 7) variable without a compiler error from Ada95.

I’m going to illustrate this with an example of storing the day number as an integer.

Charles Simonyi’s idea was that when you created an int day; to store the weekday variable you would use the name int wDay; to denote that the semantic type of this day integer was “week.” They were using “Abbreviations and Acronyms” as a sematic-type on their variables The IT managers who set policy didn’t understand the difference between semantic type (the meaning of the data) and storage type (the mechanical storage of the data) but knew Simonyi’s team was working better and the “type” as a prefix to their variables. So the convention became “thou musteth prefixth thine variable names with their types” for a long time.

I think that this was before IntelliSense and CodeCompletion were practical - error checking took a long time and this misinterpreted version of Hungarian Notation did help. My guess would be that IntelliSense and CodeCompletion came along and the practice became a redundant chore so it was abandoned mostly.

Peter’s Advice

To get the best of both worlds (and still look clever) name your int day; as dayOfWeek / dayOfMonth so that things like …

...

// day of month will be between 0 and 30 (or 1 and 31)
result->dayOfMonth = weekDay;

...

// "day of week" will be between 0 and 7
// "day of year" will be between 0 and 365 (or 1 and 366)
int dayOfWeek = (dayOfYear + 1) % 7;

...

… will look more wrong and stick out when you’re debugging.

Certainly better than;

// What is this?
result->iDayWhichMightBeSomething = iDayWhichIsSomething;
comments powered by Disqus
Peter LaValle avatar
Peter LaValle
Any links probably include affiliate ids for that sweet sweet kickback - and some programs require that I tell you. The contents of this blog are likely unrelated - as they include games, paints, and build tools.