Hung up on Hungarian naming

May 16, 2015 by Christopher Walker

And other PowerShell no-nos in my book

Yuck!

That’s what I have to say about hungarian variable naming otherwise known as hungarian notation. I will briefly explain what it is without going to far “down the rabbit hole” (consult the linked WikiPedia article). Hungarian notation is when a developer creates a new variable in any scope, they reference the type the variable will be inside the variable name. For example, say we are going to declare a string variable that will hold someone’s first name. Obviously this will have to be stored in a string type.

# In normal people notation, you would probably do something like this:
$fName = "Carl"
# -or
$firstName = "Betty"

# in hungarian notation, it would look disgusting like this:
$strFName = "Carl"
# -or
$strFirstName = "Betty"

This is a classic throwback from old school visual basic scripters who used to do this. Unfortunately I have seen the pattern carry over to those who are just now learning PowerShell. No!

NO! NO! NO!

I will admit that for example scripts posted online like on MSDN, TechNet or personal blogs, this notation may ease the understanding of the purpose of the variable. When that same notation goes into live code, it becomes a problem. Any good developer/scripter/programmer, be it the creator or reader of the code, will know the types they are dealing with or will at least be able to trace where the variable came from and how it is supposed to be used. I dealt with it in VBS simply because it wasn’t very intuitive to read (at least for me). I can’t deal with it in PowerShell because there is a method to quickly to determine what something is within the code.

Every single type in PowerShell has a method attached to it called .GetType(). If you are using PowerShell interactively, which most of us do, and you can’t figure out the type of object you are using contained in a variable, just use that. It outputs the type in a table format and even gives you the base type if it is extended from something.

PS C:\Users\christopher.CWALKDAWG> $firstName = "Carl"

PS C:\Users\christopher.CWALKDAWG> $firstName.GetType()

IsPublic IsSerial Name                                     BaseType                                                                                                
-------- -------- ----                                     --------                                                                                                
True     True     String                                   System.Object 

How cool is that?

</rant>

Privacy Policy

© 2017 | Powered by Hugo and lots of motivation.