Tuesday, November 22, 2005

Tips #2 : Variable Naming.

The next fundamental programming tip I can offer you is naming your variables appropriately. I find that a majority of logic or compile errors are caused by a misuse of variable names.

Here are some examples of bad naming conventions:
1. dim newvalue as Integer
2. int x = 0;
3. JLabel label1 = new JLabel();

Sure, laid out here, it is pretty easy to recognize what each variable does, but in a simple program of at least 500 lines of code it can prove rather difficult to track these variables.

Here are some suggestions.

In the first case, think about what newvalue represents. We know it is an integer but what is it used for? If it is a counter for a while loop, then how about doing this instead,
dim iCount as Integer
It is quite clear that this variable is of type interger and will be used as a counter.
The second example is sort of the same situation. A lot of the times one letter variables are declared in C++ and Java, for mathmatical algorithm or for loop statements. In those cases I feel it is perfectly good coding structure to use these variables as is. If this variable was to refer to a randomly produced interger used in a lottery machine, then the use of x as that variable name proves quite ambiguous.
In the third case JLabel label1 = new JLabel(); in this case, you should be more descriptive as to what label1 points to, either what sort of information is produced from this label, or where it is located.
If this label was created as the title of a program, then I would call it JLabel lblTitle = new JLabel(); If it refered to a name of a person I would declare it as JLabel lblName = new JLabel();

Pretty straight forward, and these little tips will definitly help you efficently test your code.

Also, before I forget, a few quick tips on composing your variables.
Hungarian notation is one of the most common format styles.
iNum = an integer value
dNum = a decimal value
sName = a string value
btnSubmit = a button
lblStudentAverage = a label
as Shown above, use the first initial of your variable to represent what data type it is. here are a few other examples
obj -> Object
arr -> Array
txt -> Text Box
cbx -> Combo Box

There you go, If you have any questions or comments, feel free to leave me comments.

2 Comments:

At 8:28 p.m., November 23, 2005, Anonymous Anonymous said...

I have a simple tip you might like.

When writing IF statements in languages that use the double = sign, put the constant first. So instead of:
If (iCount == 0)
//This could turn out to be iCount = 0 if you make a mistake iCount could be set to 0 and that could cause some trouble
So write:
If (0 == iCount)

So yeah thats my tip. I suggest you clean it up and maybe make a better post because me and explaining things don't work together.

 
At 9:38 p.m., November 23, 2005, Blogger Graham said...

Thanks! thats an excellent tip, and I will definitly include it in my next section.

 

Post a Comment

<< Home