On Hungarian notation for instance vs. static fields naming | Patrick Smacchia


: 2

If there is a topic I disagree with most fellow programmers, it is about instance and static fields naming guidelines. Call me old-school, but I am prefixing them with m_ and s_, or in others word I am doing Hungarian notation on fields naming. But clearly, the global consensus can be read on the MS Developer static field naming guideline:

  • Do not use a Hungarian notation prefix on static field names.

On the wikipedia Hungarian notation entry, there are two lists of advantages and disadvantages. I read them  carefully, but still I cannot change my mind to understand why the mass prefer avoiding prefix to differentiate static and instance fields. Despite all the progress made in IDE and text editor, consuming an instance field is not obviously differentiated with consuming a static fields. But in terms of behavior, a static field is something completely different than an instance field, so I need to differentiate them at a glance.

When I code review code that doesn’t follow any form of field prefixing, I found myself constantly checking, and this takes time and friction. Sure one can prefix every usages of an encapsulated instance field with the this reference, but I don’t understand: why following a guideline that applies to the N usages of a field, instead of following a guideline that applies to a single declaration?

Things can get worst if you have non encapsulated fields with name non prefixed. Callers then doesn’t know if they are using a field or a property accessor. And since, having non-encapsulated field is a very bad practice (I won’t debate here on this) having fields prefixed also make calls like obj.m_State = 3 ugly enough to make you feel that something is wrong in the API, and make you want to fix it by encapsulating the field.

In many code bases, I can see that local variables naming follow the same sort of Camel-Case naming than instance and static fields. For me as a programmer, this is pretty much a nightmare to distinguish between the 3 scopes of each state when reading a complex enough method body!!!

As a last note, everybody follows the naming guideline on interface, to prefix them with an upper I. This is actually Hungarian notation that makes it easy to distinguish classes and interfaces. But really, I don’t see any conceptual difference with field prefixing.

I understand it is a matter of habits for everyone, me included. Habits means that we rely on passion instead of relying on reasoning. But when Hungarian notation is accepted for interface naming, I wonder, why all this hate on Hungarian notation for field naming that similarly offer so significant advantages? Am I missing something?

At least, I am glad to make Ayende laugh with default NDepend rules :)