CSC/ECE 517 Fall 2010/ch5 5b jz: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
 
(38 intermediate revisions by 2 users not shown)
Line 1: Line 1:
=Variable Naming Conventions=
=Variable Naming Conventions=


==Importance of Good Variable Names==
"In computer programming, a variable is a symbolic name given to some known or unknown quantity or value, for the purpose of allowing the name to be used independently of the value it represents. A variable name in computer source code is associated with a data storage location and thus also its contents, which generally change during the course of program execution." <sup><span>[[#1foot|[1]]]</span></sup>


==Variable Naming History==
==Variable Naming History==
In the early days of computing, software was generally used for complex mathematical calculations. Most programming languages of the time resembled algebra, with short (often only one or two character) variable names. As the complexity of these algorithms grew over time, it was no longer feasible to use such non-descriptive variable names. To facilitate the needs of those programmers, new languages were developed that supported richer variable naming schemes.
While the first BASIC interpreter limited variables to a single letter and optional digit (A, B2, B3, etc.), other languages gave programmers additional room for creating more meaningful variable names. FORTRAN for instance allowed a programmer to use up to 6 characters for variable names, which was quite a leap from previous languages. <sup><span>[[#2foot|[2]]]</span></sup>  Eventually, C was introduced which allowed a programmer to use an arbitrary amount of characters for a variable name, thus giving a programmer ultimate control over their variable naming scheme.
==Importance of Strategic Variable Names==
As any programmer who has modified another's code knows, the difference between good and bad variable names can be hours of frustration attempting to make sense of someone else's work. A good set of variable naming conventions allows a programmer to focus on the logic and flow of the code, not on the meaning of strange abbreviations and what 'temp', 'temp1', and 'temp2' are really used for.
This article presents a list of guidelines and examples that a new programmer should take notice of when naming variables, classes, packages, etc. Because modern programming languages place almost no restrictions or regulations on variable names, it is more important than ever to be disciplined in your approach to naming variables.


==General Guidelines==
==General Guidelines==


===Use a Common Naming Scheme===
===Common Naming Patterns===
In a previous chapter<sup><span>[[#3foot|[3]]]</span></sup>, the authors went in depth on specific naming patterns such as CamelCase<sup><span>[[#4foot|[4]]]</span></sup>
, C-Style<sup><span>[[#5foot|[5]]]</span></sup>
, Java, and Hungarian to name a few.  While these are the more common patterns available, companies or organizations may have specific coding practices used by their coders.
 
====Under Scores====
Under scores help to separate words into an easier flowing and easier reading code.  Underscores seperate seperate words in a variable name.  Underscores can also be used to delineate constants in languages such as C.
 
string student_name;
double grade_point_average;
int _MAXHEIGHT
 
====Camel Case====
 
Camel case is a way of denoting compound variable names, and is commonly used in a wide range of languages (Java, C, C++, etc). It is characterized by capitalizing the first letter of each new word in a compound name. This method of naming variables would not normally be mixed with underscores for consistency.
 
studentName
classRank
gradePointAverage
isEnrolled


====Hungarian Notation====
====Hungarian Notation====


====Under Scores====
Hungarian notation is similar to Camel Case, but it adds they type of the variable to the front of the name. This style is helpful when there are a large number of variables in use that may have similar names, but different or ambiguous types.
 
//  String (str) for the student's name.
strStudentName   
 
//  Integer (int) for class rank.
intClassRank
 
//  Float (f) for grade point average.
fGradePointAverage
 
//  Boolean (b) for enrollment status.
bIsEnrolled
 
The examples above show the usefulness of Hungarian Notation, as it would otherwise be difficult to determine the variable type by simply looking at the names. As Integrated Development Environments (IDEs) become more powerful and user-friendly, the advantages of Hungarian Notation become less prominent (due to the automated variable type display in most modern IDEs).
 
===Stay Short and to the Point===
When thinking of variable names, you want to be descriptive enough to understand what the variable is but not too descriptive that the variable name in itself becomes 1 line of code.  By having a long variable name, it could introduce bugs and coding issues further in development.  Plus, each time you call the variable, you'll need to type the variable names out
 
GOOD EXAMPLES:
string firstName // first name of a person
string lastName // last name of a person
double windowHeight
 
BAD EXAMPLES:
string firstNameOfTheLadyMary
string super_cali_fragilistic_expialidocious
double wdwHeight // What is wdw?  If referencing this variable later it may not make sense
 
===Be Descriptive===
The above section shows the reasons to be short and to the point, but can we be too short?  Lets look at this code:
double a;
double b;
double c;
c = a * b
 
The code clearly doesn't explain what we may be computing.  We could be computing someones age in dog years, a persons Body Mass Index, or Einsteins theory of relativity but because we did not use clearly defined variables, we will never know.  As a general rule, single characters are used for temporary variables such as:
for(int i = 0; i < arraySize.length; i++)
{ // code executed in for loop
  // the i is a temporary counting variable which
  // we do not need
}
 
Lets rename our variables:


====Camel Case====
double hello;
double prettyThing;
double reNumberFactorings
reNumberFactorings = prettyThing * hello;


===Keep Names Short and to the Point===
While we used more descriptive names, we still do not know what is being computed.  Being descriptive about what values each variable will hold will make debugging code later in the life cycle of the project a much easier task.


===Use Descriptive Names===
double numberOfItems
double costOfItem;
double totalCost;
totalOfItem = numberOfItems * costOfItem;


===Explain Abbreviations with a Comment===
===Explain Abbreviations with a Comment===
Line 23: Line 101:
The last two points would seem to contradict each other, but having short and to the point names does not necessarily mean that they are less descriptive. In fact, many variable names can be shortened with the use of abbreviations to make them not only descriptive, but succinct as well. Just remember to explain any abbreviations that you have made in a comment that accompanies the declaration of the variable.
The last two points would seem to contradict each other, but having short and to the point names does not necessarily mean that they are less descriptive. In fact, many variable names can be shortened with the use of abbreviations to make them not only descriptive, but succinct as well. Just remember to explain any abbreviations that you have made in a comment that accompanies the declaration of the variable.


===Don't Use Generic Variable Names===
===Don't Be Generic===


Variables such as 'temp' or 'counter' may seem self-explanatory when first writing a block of code, but they quickly lose their meanings when re-reading that same code out of context. Avoid using generic names such as these.
Variables such as 'temp' or 'counter' may seem self-explanatory when first writing a block of code, but they quickly lose their meanings when re-reading that same code out of context. Avoid using generic names such as these.


===Use Units in Names===
===Use Units in Names===
When declaring variables which may have a unit of measurement involved, it is a good practice to include the measurement within the variable name.
double wallHeight;
double windowHeight;
As seen by the example above, is wallHeight in meters, inches, feet, or another form of measurement?  What about windowHeight?  I could be referring to the Graphical User Interface window height or am I referring to a structure which needs meters, feet or inches?
double wallHeightInMeters;
double wallHeightMeters;
double wallHeightInches;
double windowHeightpx;
There are several ways you can code the unit in the name of the variable.  Keeping it consistent throughout the entire project will save headaches later.


===Avoid Negative Logic===
===Avoid Negative Logic===


Always use positive logic when naming variables, especially in the case of boolean values. Using a name such as 'isNotEnabled' instead of 'isEnabled' only serves to confuse yourself and any future readers of the code.
Always use positive logic when naming variables, especially in the case of boolean values. Using a name such as 'isNotEnabled' instead of 'isEnabled' only serves to confuse yourself and any future readers of the code.
==References==
<span id="1foot">[[#1body|1.]]</span> http://en.wikipedia.org/wiki/Variable_(programming) <br>
<span id="2foot">[[#2body|2.]]</span> http://www.oualline.com/style/c03.html <br>
<span id="3foot">[[#3body|3.]]</span> http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch4_4c_t1 <br>
<span id="5foot">[[#4body|4.]]</span> http://en.wikipedia.org/wiki/CamelCase <br>
<span id="4foot">[[#5body|5.]]</span> http://www.cprogramming.com/tutorial/style_naming_conventions.html <br>

Latest revision as of 00:46, 3 November 2010

Variable Naming Conventions

"In computer programming, a variable is a symbolic name given to some known or unknown quantity or value, for the purpose of allowing the name to be used independently of the value it represents. A variable name in computer source code is associated with a data storage location and thus also its contents, which generally change during the course of program execution." [1]

Variable Naming History

In the early days of computing, software was generally used for complex mathematical calculations. Most programming languages of the time resembled algebra, with short (often only one or two character) variable names. As the complexity of these algorithms grew over time, it was no longer feasible to use such non-descriptive variable names. To facilitate the needs of those programmers, new languages were developed that supported richer variable naming schemes.

While the first BASIC interpreter limited variables to a single letter and optional digit (A, B2, B3, etc.), other languages gave programmers additional room for creating more meaningful variable names. FORTRAN for instance allowed a programmer to use up to 6 characters for variable names, which was quite a leap from previous languages. [2] Eventually, C was introduced which allowed a programmer to use an arbitrary amount of characters for a variable name, thus giving a programmer ultimate control over their variable naming scheme.

Importance of Strategic Variable Names

As any programmer who has modified another's code knows, the difference between good and bad variable names can be hours of frustration attempting to make sense of someone else's work. A good set of variable naming conventions allows a programmer to focus on the logic and flow of the code, not on the meaning of strange abbreviations and what 'temp', 'temp1', and 'temp2' are really used for.

This article presents a list of guidelines and examples that a new programmer should take notice of when naming variables, classes, packages, etc. Because modern programming languages place almost no restrictions or regulations on variable names, it is more important than ever to be disciplined in your approach to naming variables.

General Guidelines

Common Naming Patterns

In a previous chapter[3], the authors went in depth on specific naming patterns such as CamelCase[4] , C-Style[5] , Java, and Hungarian to name a few. While these are the more common patterns available, companies or organizations may have specific coding practices used by their coders.

Under Scores

Under scores help to separate words into an easier flowing and easier reading code. Underscores seperate seperate words in a variable name. Underscores can also be used to delineate constants in languages such as C.

string student_name;
double grade_point_average;
int _MAXHEIGHT

Camel Case

Camel case is a way of denoting compound variable names, and is commonly used in a wide range of languages (Java, C, C++, etc). It is characterized by capitalizing the first letter of each new word in a compound name. This method of naming variables would not normally be mixed with underscores for consistency.

studentName
classRank
gradePointAverage
isEnrolled

Hungarian Notation

Hungarian notation is similar to Camel Case, but it adds they type of the variable to the front of the name. This style is helpful when there are a large number of variables in use that may have similar names, but different or ambiguous types.

//  String (str) for the student's name.
strStudentName     
//  Integer (int) for class rank.
intClassRank
//  Float (f) for grade point average.
fGradePointAverage
//  Boolean (b) for enrollment status.
bIsEnrolled

The examples above show the usefulness of Hungarian Notation, as it would otherwise be difficult to determine the variable type by simply looking at the names. As Integrated Development Environments (IDEs) become more powerful and user-friendly, the advantages of Hungarian Notation become less prominent (due to the automated variable type display in most modern IDEs).

Stay Short and to the Point

When thinking of variable names, you want to be descriptive enough to understand what the variable is but not too descriptive that the variable name in itself becomes 1 line of code. By having a long variable name, it could introduce bugs and coding issues further in development. Plus, each time you call the variable, you'll need to type the variable names out

GOOD EXAMPLES:

string firstName // first name of a person
string lastName // last name of a person
double windowHeight

BAD EXAMPLES:

string firstNameOfTheLadyMary
string super_cali_fragilistic_expialidocious
double wdwHeight // What is wdw?  If referencing this variable later it may not make sense

Be Descriptive

The above section shows the reasons to be short and to the point, but can we be too short? Lets look at this code:

double a;
double b;
double c;
c = a * b

The code clearly doesn't explain what we may be computing. We could be computing someones age in dog years, a persons Body Mass Index, or Einsteins theory of relativity but because we did not use clearly defined variables, we will never know. As a general rule, single characters are used for temporary variables such as:

for(int i = 0; i < arraySize.length; i++) 
{ // code executed in for loop
  // the i is a temporary counting variable which
  // we do not need
}

Lets rename our variables:

double hello;
double prettyThing;
double reNumberFactorings
reNumberFactorings = prettyThing * hello;

While we used more descriptive names, we still do not know what is being computed. Being descriptive about what values each variable will hold will make debugging code later in the life cycle of the project a much easier task.

double numberOfItems
double costOfItem;
double totalCost;
totalOfItem = numberOfItems * costOfItem;

Explain Abbreviations with a Comment

The last two points would seem to contradict each other, but having short and to the point names does not necessarily mean that they are less descriptive. In fact, many variable names can be shortened with the use of abbreviations to make them not only descriptive, but succinct as well. Just remember to explain any abbreviations that you have made in a comment that accompanies the declaration of the variable.

Don't Be Generic

Variables such as 'temp' or 'counter' may seem self-explanatory when first writing a block of code, but they quickly lose their meanings when re-reading that same code out of context. Avoid using generic names such as these.

Use Units in Names

When declaring variables which may have a unit of measurement involved, it is a good practice to include the measurement within the variable name.

double wallHeight;
double windowHeight;

As seen by the example above, is wallHeight in meters, inches, feet, or another form of measurement? What about windowHeight? I could be referring to the Graphical User Interface window height or am I referring to a structure which needs meters, feet or inches?

double wallHeightInMeters;
double wallHeightMeters;
double wallHeightInches;
double windowHeightpx;

There are several ways you can code the unit in the name of the variable. Keeping it consistent throughout the entire project will save headaches later.

Avoid Negative Logic

Always use positive logic when naming variables, especially in the case of boolean values. Using a name such as 'isNotEnabled' instead of 'isEnabled' only serves to confuse yourself and any future readers of the code.

References

1. http://en.wikipedia.org/wiki/Variable_(programming)
2. http://www.oualline.com/style/c03.html
3. http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch4_4c_t1
4. http://en.wikipedia.org/wiki/CamelCase
5. http://www.cprogramming.com/tutorial/style_naming_conventions.html