Good Examples of Hungarian Notation? [closed]
Asked Answered
I

22

17

This question is to seek out good examples of Hungarian Notation, so we can bring together a collection of these.

Edit: I agree that Hungarian for types isn't that necessary, I'm hoping for more specific examples where it increases readability and maintainability, like Joel gives in his article (as per my answer).

Indention answered 14/10, 2008 at 17:37 Comment(1)
This question was created when Stack Overflow was first started and is really not the type of question allowed today for this site. It is still a useful resource and should be kept for historical reasons and the draws it brings to the site.Indention
I
29

The now classic article, as mentioned in other Hungarian posts, is the one from Joel's site:

http://www.joelonsoftware.com/articles/Wrong.html

Indention answered 14/10, 2008 at 17:38 Comment(0)
R
40

The problem with asking for good examples of Hungarian Notation is that everyone's going to have their own idea of what a good example looks like. My personal opinion is that the best Hungarian Notation is no Hungarian Notation. The notation was originally meant to denote the intended usage of a variable rather than its type but it's usually used for type information, particularly for Form controls (e.g., txtFirstName for a text box for someone's first name.). This makes the code less maintainable, in terms of readability (e.g., "prepIn nounTerms prepOf nounReadability") and refactoring for when the type needs to be changed (there are "lParams" in the Win32 API that have changed type).

You should probably consider not using it at all. Examples:

  • strFirstName - this can just be firstName since it's obvious what it's for, the type isn't that important and should be obvious in this case. If not obvious, the IDE can help you with that.
  • txtFirstName - this can change to FirstNameTextBox or FirstName_TextBox. It reads better and you know it's a control and not just the text.
  • CAccount - C was used for class names in MFC but you really don't need it. Account is good enough. The uppercase name is the standard convention for types (and they only appear in specific places so they won't get confused with properties or methods)
  • ixArray (index to array) - ix is a bit obscure. Try arrayIndex.
  • usState (unsafe string for State) - looks like "U.S. State". Better go with state_UnsafeString or something. Maybe even wrap it in an UnsafeString class to at least make it type-safe.
Reserpine answered 14/10, 2008 at 17:38 Comment(7)
I agree that we should use it for intented usage, and that's what I'm hoping people will contribute, as for my forthcoming application I'd like to create a standard from the get go.Indention
The last point presented here is the first thing that popped into my mind after reading Joel's original article. This is one of the purposes of class hierarchies, and using naming conventions to do it is not optimal.Vaulting
It's worth to mention the General Naming Conventions at MSDN (msdn.microsoft.com/en-us/library/ms229045.aspx). They say "Do not use Hungarian notation".Pickmeup
@gutofb7: your link is for .NET. This is not a .NET specific question. We all should understand why this recommendation has been made (think "Code Definition Window") before trying to apply this argument for all the environments and languages. There are places where correctly used AppHungarian is a blessing, and all other methods mentioned here (class hierarchies, using extra long names, encoding type information in there) are inferior to it.Zoarah
In PHP, not all types are obvious just from the variable name. What about a bank sort code $BankSortCode? Is it "int", or a "string" because it has hyphens? A user's height $UserHeight? Could be "int" if it's in mm, but what if it's in feet/inches and is a "string" to accommodate the words feet/inches, or " ', or the dot? I use underscore with camelCase - $int_BankSortCode, $str_UserName, $ary_TeamNames. Your answer is not really a valid one to cater for all languages or scenarios. Although I accept it is, as you stated yourself, just an opinion.Armenta
You can make all kinds of arguments that make certain benefits of coding practices seem superfluous. Lets take CamelCase... Why do we need to lowercase the beginning of the variable? Why uppercase the next words? userName = UserName = username, they're all just as easy to read and understand. Consistency is key when you're using coding conventions, that's the most important thing, and suggesting that Hungarian Notation is somehow worse, is just ignoring that all coding conventions are valid and useful, if followed consistently.Voleta
If Hungarian Notation is uses consistently with it's original intent of showing intent, then fine. But a FOOLISH consistency is a hobgoblin of young programmer's minds.Reserpine
I
29

The now classic article, as mentioned in other Hungarian posts, is the one from Joel's site:

http://www.joelonsoftware.com/articles/Wrong.html

Indention answered 14/10, 2008 at 17:38 Comment(0)
C
19

p

(for pointer). Its pretty much the only prefix I use. I think it adds a lot to a variable (eg that its a pointer) and so should be treated a little more respectfully.

Hungarian for datatypes is somewhat passe now IDEs can tell you what the type is (in only a few seconds hovering over the variable name), so its not so important. But treating a pointer as if its data is not good, so you want to make sure it's obvious to the user what it is even if he makes assumptions he shouldn't when coding.

Convertite answered 14/10, 2008 at 17:45 Comment(3)
Yep, this is about the only time I'd consider using Hungarian notation too.Physics
I agree, although I find it much better to put _p at the end. It makes pointer dereferences of structs so much easier to read, e.g. some_struct_p->some_member (and some_struct_p.some_member would stand out as obviously wrong (in the Joel's article meaning)).Oarfish
I had a similar question too, and I came to somewhat similar conclusions. Write-up here [autumn 2014].Galactometer
P
15

t

Tainted data. Prefix all data incoming from an untrusted source to make that variable as tainted. All tainted data should be cleansed before any real work is done on it.

Primordium answered 14/10, 2008 at 17:57 Comment(0)
S
9

It's pointless to use Hungarian to indicate types because the compiler already does it for you.

Where Hungarian is useful is to distinguish between logically different sorts of variables that have the same raw type. For example, if you are using ints to represent coordinates, you could prefix x coordinates with x, y coordinates with y and distances with d. So you would have code that looks like

dxHighlight = xStart - xEnd

yHighlight = yLocation + 3

yEnd = yStart + dyHeight

dyCode = dyField * 2

and so on. It's useful because you can spot errors at a glance: If you add a dy to a y, you always get a y. If you subtract two x's you always get a dx. If you multiply a dy by a scalar, you always get a dy. And so on. If you see a line like

yTop = dyText + xButton

you know at a glance that it is wrong because adding a dy and a x does not make sense. The compiler could not catch this for you because as far as it can tell, you are adding an int to an int which is fine.

Sansom answered 30/11, 2008 at 5:52 Comment(5)
I do this as well, except as a suffix most of the time: startX, endY, vertexZ.Crystallize
xEnd = xStart + dyField; // make region be square That looks wrong, but it seems perfectly valid.Denton
@Denton : in this case you have to use another variable with a more consistent name (like dxField = dyField; xEnd = xStart + dxField;Biff
"It's pointless to use Hungarian to indicate types because the compiler already does it for you." This assumes you are catching it at compile time. I've recently found some benefit to using occasional hungarian notation in JavaScript and when dealing with variant types. I also found hungarian notation very helpful when i write assembly. That said, they're useless for non simple intents; it's nice to know whether its a number or a string, or whether it's string or a pointer to a single byte, but it's useless to distinguish different HashMap<string, object>.Lovejoy
My argument is that there is merit to hungarian notation, but it becomes useless (1) your notation is very clear and easy to find reference to quickly. (2) your notation is very lean and lacks synonyms. hungarian notation isn't suppose to uniquely distinguish every object type, but help hint at important things to know about the identifier without having to open a fancy editor.Lovejoy
V
6

Do not use language specific prefixes.

We use:

n: Number 
p: Percentage 1=100% (for interest rates etc)
c: Currency
s: String
d: date
e: enumeration
o: object (Customer oCustomer=new Customer();)
...

We use the same system for all languages:

SQL
C
C#
Javascript
VB6
VB.net
...

It is a life saver.

Ventricular answered 29/11, 2008 at 8:4 Comment(4)
p as a prefix in languages that support pointers, but not meaning pointer... scary!Venus
We don't use pointers much (if any) anymore. In our line of work use see a lot of interest rates (percentage) and no pointers. The idea though is to use cross language prefixes. It is not the specific prefixes that count. Pick your own.Ventricular
I use enSomething not just eSomethingG
I use enSomething for the variable that contains the enumeration.Ventricular
L
6

I was strongly against Hungarian notation until I really started reading about it and trying to understand it's original intent.
After reading Joels post "Wrong" and the article "Rediscovering Hungarian Notation" I really changed my mind. Done correct I belive it must be extremly powerful.

Wrong by Joel Spolsky
http://www.joelonsoftware.com/articles/Wrong.html

Rediscovering Hungarian Notation
http://codingthriller.blogspot.com/2007/11/rediscovering-hungarian-notation.html

I belive that most Naysayers have never tried it for real and do not truly understand it. I would love to try it out in a real project.

Ladykiller answered 8/9, 2010 at 12:27 Comment(2)
According to the linked article rg_opbk[i].close is more clear than open_books_list[index].close. Somebody is lying to themself.Shreve
In sum, HN helps you spot mistakes that compiler cannot, like mixing safe and unsafe data, row and column coordinates, array indices and array elementsNaima
P
5

Devil's Advocate: The best example of Hungarian notation is not to use it. :D

We do not gain any advantage to using Hungarian notation with modern IDEs because they know the type. It adds work when refactoring a type for a variable since the name would also have to be changed (and most of the time when you are dealing with a variable you know what type it is anyway).

You can also get into ordering issues with the notation. If you use p for pointer and a for address do you call your variable apStreet or paStreet? Readability is diminished when you don't have consistency, and you have to use up valuable mind space when you have to remember the order that you have to write the notation in.

Primordium answered 14/10, 2008 at 17:49 Comment(2)
I agree that you don't need to use it for all types, I'm hoping for good examples like Joel gives, where it adds to the readability and usability.;Indention
Hungarian notation should not be used for types. You are completely correct there. However, the original intention was to use it for things not specified by types, and there are potential uses there.Lapwing
P
5

I find hungarian notation can sometimes be useful in dynamic languages. I'm specifically thinking of Server Side Actionscript (essentially just javascript), but it could apply elsewhere. Since there's no real type information at all, hungarian notation can sometimes help make things a bit easier to understand.

Preposterous answered 14/10, 2008 at 17:51 Comment(0)
H
5

Hungarian notation (camel casing, as I learned it) is invaluable when you're inheriting a software project.

Yes, you can 'hover' over a variable with your IDE and find out what class it is, but if you're paging through several thousand lines of code you don't want to have to stop for those few seconds - every.... single.... time....

Remember - you're not writing code for you or your team alone. You're also writing it for the person who has to pick up this code 2-5 years down the road and enhance it.

Hirokohiroshi answered 14/10, 2008 at 18:18 Comment(3)
it's only useful if you include a legend for the prefixes otherwise they might be too cryptic for a future reader.Reserpine
Camel Casing and Hungarian Notation are different things. Camel Casing is just doingThisWithYourNames (each word starts with a capital letter). Hungarian notation involves prepending some type ID to the name.Preposterous
Interesting. I was originally under the assumption they were the same because we always used the same prefixes (str, int, dbl, obj, dat, etc) and that was in two different places.Hirokohiroshi
J
4

I think the key thing to take away from Joel's article, linked above, and Hungarian Notation in general, is to use it when there's something non-obvious about the variable.

One example, from the article, is encoded vs non encoded strings, it's not that you should use hungarian 'us' for unsafe strings and 's' for safe strings, it's that you should have some identifier to indicate that a string is either safe or not. If it becomes standard, it becomes easy to see when the standard is being broken.

Jumpy answered 14/10, 2008 at 18:55 Comment(0)
A
3

The only Hungarian that's really useful anymore is m_ for member variables. (I also use sm_ for static members, because that's the "other" scope that still exists.) With widescreen monitors and compilers that take eight-billion-character-long variable names, abbreviating type names just isn't worth it.

Almund answered 14/10, 2008 at 18:17 Comment(0)
P
2

m

When using an ORM (such as hibernate) you tend to deal managed and unmanaged objects. Changing an managed object will be reflected in the database without calling an explicit save, while dealing with a managaged object requires an explicit save call. How you deal with the object will be different depending on which it is.

Primordium answered 14/10, 2008 at 18:2 Comment(0)
H
2

I find that the only helpful point is when declaring interface controls, txtUsername, txtPassword, ddlBirthMonth. It isn't perfect, but it helps on large forms/projects.

I don't use it for variables or other items, just controls.

Hyacinthhyacintha answered 14/10, 2008 at 18:9 Comment(0)
L
2

In addition to using 'p' for pointer, I like the idea of using 'cb' and 'cch' to indicate whether a buffer size parameter (or variable) is a count of bytes or a character count (I've also seen - rarely - 'ce' used to indicate a count of elements). So instead of conveying type, the prefix conveys use or intent.

I admit, I don't use the prefix as consistently as I probably should, but I like the idea.

Liba answered 14/10, 2008 at 18:30 Comment(0)
A
2

A very old question, but here's a couple of "Hungarian" prefixes I use regularly:

my

for local variables, to distinguish locality where the name might make sense in a global context. If you see myFoo, it's only used in this function, regardless of anything else we do with Foos anywhere else.

myStart = GetTime();
doComplicatedOperations();
print (GetTime() - myStart);

and

tmp

for temporary copies of values in loops or multi-step operations. If you see two tmpFoo variables more than a couple of lines from each other, they're almost certainly unrelated.

tmpX = X; 
tmpY = Y;
X = someCalc(tmpX, tmpY);
Y = otherCalc(tmpX, tmpY);

and sometimes old and new in for similar reasons to tmp, usually in longer loops or functions.

Atonal answered 28/5, 2009 at 0:4 Comment(0)
F
2

Well, I use it only with window control variables. I use btn_, txt_, lbl_ etc to spot them. I also find it helpful to look up the control's name by typing its type (btn_ etc).

Freehand answered 21/2, 2013 at 8:21 Comment(0)
C
1

I only ever use p for a pointer, and that's it. And that's only if I'm in C++. In C# I don't use any hungarian notation. e.g.

MyClass myClass;
MyClass* pMyClass;

That's all :)

Edit: Oh, I just realised that's a lie. I use "m_" for member variables too. e.g.

class
{
private:
bool m_myVar;
}
Chinaman answered 14/10, 2008 at 18:1 Comment(0)
A
1

I agree that Hungarian notation is no longer particularly useful. I thought that its original intention was to indicate not datatype, but rather entity type. In a code section involving the names of customers, employees and the user, for example, you could name local string variables cusName, empName and usrName. That would help distinguish among similar-sounding variable names. The same prefixes for the entities would be used throughout the application. However, when OO is used, and you're dealing with objects, those prefixes are redundant in Customer.Name, Employee.Name and User.Name.

Adulteress answered 14/10, 2008 at 20:33 Comment(1)
not just datatype also the scope .... :)G
C
1

The name of the variable should describe what it is. Good variable naming makes Hungarian notation useless.

However, sometimes you'd use Hungarian notation in addition to good variable naming. m_numObjects has two "prefixes:" m_ and num. m_ indicates the scope: it's a data member tied to this. num indicates what the value is.

I don't feel hindered at all when I read "good" code, even if it does contain some "Hungarian." Right: I read code, I don't click it. (In fact, I hardly use my mouse ever when coding, or any voodoo programming-specific lookup features.)

I am slowed when I read things like m_ubScale (yes, I'm looking at you, Liran!), as I have to look at its usage (no comments!) to find out what it scales (if at all?) and it's datatype (which happens to be a fixed-point char). A better name would be m_scaleFactor or m_zoomFactor, with a comment as a fixed-point number, or even a typedef. (In fact, a typedef would be useful, as there are several other members of several classes which use the same fixed-point format. However, some don't, but are still labeled m_ubWhatever! Confusing, to say the least.)

I think Hungarian was meant to be an additive to the variable name, not a replacement for information. Also, many times Hungarian notation adds nothing at all to the variable's readability, wasting bytes and read time.

Just my 2¢.

Crystallize answered 30/11, 2008 at 6:54 Comment(0)
G
0

There's no such thing as a good example of hungarian notation. Just don't use it. Not even if you are using a weakly typed language. You'll live happier.

But if you really need some reason not to use it, this is my favourite one, extracted from this great link:

One followon trick in the Hungarian notation is "change the type of a variable but leave the variable name unchanged". This is almost invariably done in windows apps with the migration from Win16 :- WndProc(HWND hW, WORD wMsg, WORD wParam, LONG lParam) to Win32 WndProc(HWND hW, UINT wMsg, WPARAM wParam, LPARAM lParam) where the w values hint that they are words, but they really refer to longs. The real value of this approach comes clear with the Win64 migration, when the parameters will be 64 bits wide, but the old "w" and "l" prefixes will remain forever.

Galasyn answered 14/10, 2008 at 17:57 Comment(0)
I
0

I find myself using 'w' meaning 'working', as a prefix instead of 'temp' or 'tmp', for local variables that are just there to jockey data around, like:

Public Function ArrayFromDJRange(rangename As Range, slots As Integer) As Variant

' this function copies a Disjoint Range of specified size into a Variant Array 7/8/09 ljr

Dim j As Integer
Dim wArray As Variant
Dim rCell As Range

wArray = rangename.Value ' to initialize the working Array
ReDim wArray(0, slots - 1) ' set to size of range
j = 0

For Each rCell In rangename
    wArray(0, j) = rCell.Value
    j = j + 1
Next rCell

ArrayFromDJRange = wArray

End Function
Indention answered 8/7, 2009 at 17:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.