Comments
Richard Davies wrote: The UK has a good crop of technology pioneers in cloud computing - for example ElasticHosts, FlexiScale, Flexiant, OnApp - and also some strong government initiatives such as G-Cloud. We will have to see whether this kind of technical leadership converts into swift mass-market adoption or not.
Cloud Expo on Google News


2008 West
DIAMOND SPONSOR:
Data Direct
SOA, WOA and Cloud Computing: The New Frontier for Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
GOLD SPONSORS:
Appsense
User Environment Management – The Third Layer of the Desktop
Cordys
Cloud Computing for Business Agility
EMC
CMIS: A Multi-Vendor Proposal for a Service-Based Content Management Interoperability Standard
Freedom OSS
Practical SOA” Max Yankelevich
Intel
Architecting an Enterprise Service Router (ESR) – A Cost-Effective Way to Scale SOA Across the Enterprise
Sensedia
Return on Assests: Bringing Visibility to your SOA Strategy
Symantec
Managing Hybrid Endpoint Environments
VMWare
Game-Changing Technology for Enterprise Clouds and Applications
Click For 2008 West
Event Webcasts

2008 West
PLATINUM SPONSORS:
Appcelerator
Get ‘Rich’ Quick: Rapid Prototyping for RIA with ZERO Server Code
Keynote Systems
Designing for and Managing Performance in the New Frontier of Rich Internet Applications
GOLD SPONSORS:
ICEsoft
How Can AJAX Improve Homeland Security?
Isomorphic
Beyond Widgets: What a RIA Platform Should Offer
Oracle
REAs: Rich Enterprise Applications
Click For 2008 Event Webcasts
SYS-CON.TV
Top Links You Must Click On


Hungarian Notation with Java
Hungarian Notation with Java

Creating software can be considered an art form, requiring all of the characteristics associated with an artist, such as creative style. Most artists, however, aren't required to modify their creations after the work has been purchased. Software, on the other hand, needs to be maintained either by its creator or by others if the creator has moved to other responsibilities.

The maintainability of software is an increasingly important issue. As industry demand for programmers' skills increases, so does their turnover rate within a company, thus diminishing the likelihood of the original programmer's being available when a problem arises or when the product needs to be enhanced. Also, a programmer who produces volumes of code may need some time to refamiliarize him- or herself with code that was written only a month earlier, perhaps, but hundreds of lines ago.

Programmers exposed to code that has a style different from their own may institute parts of the new style into their own code if there's an obvious advantage. Most programmers restyle inherited code to their own conventions. New programmers should thus be exposed to good coding style and its advantages before any code is written.

Hungarian Notation
One useful coding technique benefiting both code readability and writability ­ and hence maintainability ­ is Hungarian Notation. This technique is suitable for C/C++ programs that make use of pointers. It's also applicable to Java programs. Essentially, Hungarian Notation is a naming convention that allows a programmer to determine the type of variable or constant just by looking at its name. The letter "i", for example, can be used to denote an "int". By prefixing an "int" variable named "count" with an "i" as in "iCount", a programmer can tell by looking at the variable name that the variable is of type "int".

As an example, look at the following code segment:

float x = 0;
int y = 0;

x = y;

Looking only at the statement "x = y", someone attempting to understand this code might assume that both variables are of the same type. A good guess would be that x and y are coordinate variables of type "int". However, we don't know if x and y are objects, numbers or characters. This is especially true if the declarations for x and y are not physically close to the assignment statement. You'd need to search through the code looking for the declarations. If the original programmer had used Hungarian Notation, the statements would look like this:

float fX = 0;
int iY = 0;

fX = iY;

A person reading just the statement "fX = iY" can deduce that an "int" is being assigned to a "float" and may suspect that the code is a little out of the ordinary. Now look at these statements:

int iX = 0;
float fY = 0;

iX = fY;

From reading just the statement "iX = fY", a person can now deduce that a float is being assigned to an integer and be very concerned. Because of a type mismatch this program won't compile successfully.

As a side benefit, Hungarian Notation allows the original programmer to recognize that an explicit cast is required in an assignment statement while the code is being written. A programmer writing the above statement would notice that "iX" and "fY" were of different types and would insert a cast "(int)" before entering the right side of the assignment, as in "iX = (int)fY", or might change "iX" to a float variable, "fX".

This is the writability aspect of using Hungarian Notation, in which errors are detected and removed as the code is written. Discovering errors earlier in the development cycle is a natural benefit.

Reuse of Variable Names
Hungarian Notation also allows variable names to be reused when only the notation part of the name is different. Let's take a look at a slightly more complex example, shown in Listing 1. In this class the constructor is given a file name and a "boolean." The file name is the name of a file and the boolean is used to tell the constructor whether the file name should be used.

String strCancel = new String(); // The ŒCancel' string
Button btnCancel = new Button( strCancel ); // The cancel button

The following statements ask a user to enter a user ID. A JLabel is used to identify a JTextField as the place to enter the user ID. Both variables are named "Userid" but are distinguished by their particular data type notation.

JLabel labelUserid = new JLabel
( "Enter your user id here:" );
JTextField fieldUserid = new JTextField();

Search and Replace
When writing new code or upgrading existing code, notated variables are readily modifiable. For instance, a text editor's replace utility can rename all instances of a variable named "iW" to "iX" in one operation. However, the same operation can't be used to rename variable "w" to "x" without errors as all instances of the letter "w" would be replaced whether or not it represents a variable.

Variable Naming Conventions
The following is a suggested set of rules for generating variable names and is not meant to be a rigid set.
1. The prefix should be determined from the datatype definition.
2. The prefix should be in lowercase only.
3. If the variable is declared inside a class as instance data, the prefix should be prefixed by an underscore as in "_fVarName".
4. All words in the variable name should be capitalized to increase readability, starting with the first letter after the notation prefix.
5. Don't overdo it. If you have a single JPanel, name it "panel."
6. For longer type names such as FontMetrics, use either an acronym such as "fm" or a portion of the name such as "metric."

Here are some name prefix suggestions:
Primitive Types
Type - Notation - Example
int - i - iIndex
short - s - sIndex
char - c - cLetter
boolean - b - bFound
byte - y - yData
float - f - fInches

Arrays
Append the letter "a" to the type prefix:
byte[] - yaNumbers;
int[] - iaNumbers;
String[] - straNames;

Object Types
Integer - intIndex;
String - strIndex;
StringBuffer - strbIndex;
Point - ptIndex;
Boolean - boolFound;
Label - labelTextString;
TextField - fieldName;
Panel - panelTextArea;
Frame - frameWindow;
Window - wndPrompt;
Popup - popSelection;
MyOwnObjectType - mootPoint;

Container Objects
Prefix a notation for the object type to the notation for the variable type.
Vector vintIndices;
// Vector of Integer objects
Hashtable hashserAddresses;
// Hashtable of Serializable address
objects

Instance Variables
Add an underscore before the type prefix and the variable name.
byte[] - _yaNumbers;
int - _iIndex;
boolean - _bFound;
float - _fInches;
String - _strName;

As an alternative, another designation such as "m_" can be added to the beginning of a variable name to indicate an instance (member) variable.
byte[] - m_yaNumbers;
int - m_iIndex;
boolean - m_bFound;
float - m_fInches;
String - m_strName;

Class Variables
Prefix a "c_" to the name.

int - c_iIndex;
double - c_dValue;

A Life Example
Say tomorrow someone came to you and said a fellow developer is unable to complete a critical piece of code and you're the only person who has the skills and knowledge to finish the job ­ and by the way, you only have until the end of the week to complete the task. Otherwise the customer will cancel the contract and take that six-figure sum elsewhere. Before you panic, you decide to evaluate the situation by reading a sample of the code. You need to find out whether it looks reliable and whether you can understand it well enough to modify it. The answers to these questions, multiplied by a hundred, will give you a good idea of how you'll react when asked to inherit the entire class library. You arbitrarily turn to the function shown in Listing 2. What does it do?

This code is actually part of a text editor class that searches for a given string with optional case sensitivity within a vector of string buffers beginning at an x and y coordinate. The "result" returned is the point coordinate of the found text, y being the row and x being the column, or (-1, -1) if the text string isn't found. From this code we can deduce several things:
1. The original programmer was kind enough to use understandable variables, not just "s"or "zx".
2. The variables "numberOfLines," "lines" and "cursor" aren't declared in the function so they're probably instance or class variables, but we're not really sure and we'll have to hunt for them.
3. The author may have had difficulty with variable naming since there are similarly named variables "line," "lines" and "line1".
4. The variable "lines" is probably a "Vector" since on line 25 we see a "lines.elementAt()" function call. Then again, it could be a "DefaultListModel".
5. The variable "cursor" is probably a "Point" since on lines 8 and 9 we see "cursor.x" and "cursor.y". However, it could also be an "Event" object or, less likely, a "Rectangle" object.
6. The variable "numberOfLines" is probably an "int" since it's being assigned to another "int" on line 23.

Looking at the individual statements from line 25 to line 29, it's difficult to determine whether the type assignments are correct and the method calls against the variables are appropriate. Could this be the real source of the term fuzzy logic?

Now compare the code in Listing 2 to the same code in Listing 3, which has been written using Hungarian Notation.

Several things are worth noticing here:
1. The "cases" variable has been replaced with "bCase", which clearly defines the variable as a "boolean" intended to mean case sensitivity. Since "case" is a keyword, the original author couldn't use it as a variable name, which is probably why the variable was originally named "cases".
2. The variables "_iNumberOfLines", "_vstrbLines" and "_ptCursor" are clearly defined as instance variables of type "int", "Vector" and "Point", respectively.

In this example an underscore character prefix distinguishes the instance variables from the local variables and function arguments. Also, the letter "b" is used as the notation prefix for boolean type variables, as in "_bNameIsValid". The variable name "strFilename" is used for both the input argument and the instance variable with the exception of the underscore prefix in the instance variable. If you just see the statements:

_strFilename = strFilename;
_bNameIsValid = true;

you can tell immediately which variables are instance variables, booleans or strings, and ­ if the original programmer used sensible variable names ­ the purpose of each variable. Most important, the assignment statements look correct from a "type" point of view: a "String" is assigned a "String," and a "boolean" is assigned a "boolean" constant.

The same variable name can also be used for related variables. The Hungarian Notation prefix provides a distinction between the data type of the variables. For instance, the following two state variables represent the string for a "Cancel" button and the Button object itself.

3. The variables named "line", "lines" and "line1" have been replaced by "strbLine", "vstrbLines" and "strLine", signifying a "StringBuffer", a "Vector" of StringBuffers and a "String". The same root name "Lines" has been reused for all three variables, which eliminates the extra step of having to think up different but similar variable names that represent the storage of a text string.

Each statement from line 25 to line 29 can now be examined individually, out of context, to determine whether each line's syntax is correct. For example, let's visit line 25.

25 strbLine = (StringBuffer)_vstrbLines.elementAt( i );

Here's what we can deduce:
1. The function "elementAt()" is correctly called against the object "_vstrbLines" since the "v" indicates a "Vector".
2. The argument type to the function "elementAt()" is correct since the variable "i" is an "int".
3. The "(StringBuffer)" cast against "_vstrbLines.elementAt(i)" is correct since the "Vector" holds objects of type "StringBuffer" as indicated by the "strb" in "_vstrbLines".
4. The left side of the assignment statement is also correct since the result of the cast is being assigned to a "StringBuffer" as indicated by the "strb" in "strbLine".

The statement is clear and easier to read because it contains more information than the original. More important, it's easier to write because as a developer who uses Hungarian Notation consistently, you can tell the statement is correct as you write it.

Summary
Differences in artistic coding style can vary greatly among programmers. The personal aspects of coding style are associated with pride of ownership. However, a lack of standards can indirectly produce code that has unknown reliability characteristics and is hard to maintain. The result can be unplanned work of unknown duration, which includes tasks ranging from documenting to rewriting. It's financially beneficial to use accepted coding techniques, such as Hungarian Notation, consistently. This will provide long-term time savings. Its use can result in code that is more readable, writable, understandable and thus more maintainable, transferable and reliable. Think about this the next time you inherit someone else's code or would like to pass on some of your own code to that person who's looking over your shoulder.

About Brian Farn
Brian Farn researches and develops Java software at IBM and is currently associated with the IBM VisualAge for Java team at the IBM Software Solutions Toronto Laboratory. He is a
graduate of the University of Western Ontario with degrees in physics and electrical engineering.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

Enterprise Open Source Magazine Latest Stories . . .
Apache Deltacloud, the Red Hat-contributed ReSTful API that abstracts differences between clouds so services on any cloud can be managed – provided of course there’s a driver – has graduated from the Apache Foundation’s incubator and is now a full-fledged Top-Level Project (TLP). The...
With Cloud Expo 2012 New York (10th Cloud Expo) just four months away, what better time to start introducing you in greater detail to the distinguished individuals in our incredible Speaker Faculty for the technical and strategy sessions at the conference... We have technical and st...
AMD said late Tuesday that its chief sales officer Emilio Ghilardi had left the company and that CEO and president Rory Read is going to do his job while a replacement is sought. AMD didn’t say why Ghilardi left but it’s assumed Read wants his own people. Read is relatively new to th...
During the lifespan of M3 (Monitis Monitor Manager) there has always been something lacking – timers. M3 execution procedure was outlined in this previous article. The execution mentioned in the latter was a one-time-execution, whereas server monitoring requires periodic invocati...
Red Hat is putting its bought-in Gluster scale-out NAS storage technology, acquired in October, on the Amazon cloud. It’s styled Red Hat Virtual Storage Appliance for Amazon Web Services and other clouds are supposed to follow in short order.
A new episode of the screencast series is now available at the OpenNebula YouTube Channel. This screencast demonstrates the new easily-customizable self-service portal for cloud consumers. Its aim is to offer a simplified access to shared infrastructure for non-IT end users. The scree...
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


SYS-CON Featured Whitepapers
ADS BY GOOGLE