Naming Your Variables

Status
Not open for further replies.

EN0

Member
This thread focuses on naming or defining variables appropriately when you program code. This is commonly viewed as an unimportant aspect that we reluctantly do just to get on with our program. Sometimes we never consider what others might first think upon reading a particular variable. Hopefully, you will attain a different view and practice of naming variables once you read this tutorial.

Why It’s Important

Have you ever named a variable something completely irrelevant to its primary function? Perhaps you wanted to light an LED and called the output port TNT or Top_Secret. This might be quite sufficient for your purposes, but if you ever share your code with someone else or ask for help they probably would have no clue as to what it is for. In fact, you might not even recognize it yourself after a couple years. Therefore, you should always attempt to name or define your variables that suggest their obvious function in your code.

Advice On How to Get Started

One of the first pieces of advice has been already mentioned; that is, naming your variables according to their fundamental purpose. A common misconception of categorically naming variables is how long or short you should entitle them. It is recommended that you do not inhibit the length of a variable, otherwise it will result in a misunderstanding of their function. Complex names or numerical signs aren't advised, since it might impede comprehension. Your variables should be simple and straight to the point.

Another important concept to remember is how our brains organize information and what triggers our memories. Now this is where it gets very interesting! As you continue to practice naming variables, your brain commences organizing the names with their significance. What exactly does that mean? Well, let me provide an example.

First let’s consider that variable we previously decided to symbolize our I/O port going to an LED. As part of our application, the LED will continuously blink to inadvertently represent a sophisticated security system that will keep predators away by bluffing. After contemplating on the hardware and requirements for our simple application, we come to the conclusion that only one LED is required for an effective solution. Therefore, we could name our variable simply as LED, but only due to the fact that one LED is being used. If this is your first coding project and you need assistance, then whoever is helping you can automatically connect with what you are doing by using that variable name. The name implies that you are controlling an LED as part of your hardware on your I/O pin. To confirm this assumption, anyone who is helping you can quickly glance in your #define section and see whether you set it as your output port (TRIS or GPIO, depends on PIC). If you had used the name TNT, a person’s brain wouldn’t emphasize remembering that name in association with its function because it’s completely irrelevant.

Triggers

If you wanted to remember a meeting you have at 12:00 PM, you can think of “noon” or “lunch” to prompt a trigger. Whenever you think of those words, it will effectively stimulate a thought that indicates you have a meeting at that time. Therefore, try to organize specific triggers that might stimulate thoughts relevant to your variable name. This is a useful trick when you adjust your code in the future; since you will be more likely remember the variable names and what they do. Likewise, try to think of variable names that might trigger accurate functions in your code so that others may easily understand it.

Now you see how important it is to appropriately and effectively name your variables, for your benefit and for other people’s as well.

Any suggestions, comments, or advice is encouraged!
 
Last edited:

I'm going to disagree with this bit as I believe that shortening variables is a bad thing. If I have a complex piece of code then I fing that debugging takes 90% of the time and so the initial typing time is irrelevant. Clear meaningful names are one of the most important parts of coding.

I tend to stick to the C convention now.
CONSTANTS are in capitals. I.E PORTB has the constant value 6.
variables are lower case. I.E portb is the value on the port.
actionFunctions start lower case and normaly with a verb (get, put, send, write) followed by a capitalised Function (Lcd, Rs232, Port, Action) etc. These are hard to stick to the convention but close is good enough. I.E getKeypad() putRs232() writeLcd() openCanOfWorms() etc.

Interestingly BoostC uses the convention yet C18 doesn't.
So in BoostC, PORTB is the address of the port (a constant) and portb is the value held in location PORTB (a variable). In C18 they just use PORTB for the value.

Mike.
 
Pommie-
I prefer (where possible) to do the names in good old librarian format; category first, specific last.
So that would be LCD_write() and LCD_read().

Mainly this is useful as compilers often display variables and functions sorted alphabetically, so they are all neatly grouped under LCD_xxx.

It also has some benefits when searching for a text string "LCD_" will bring up anything in that category.
 
I note that you didn't quote my last function name. openCanOfWorms().

Mike.
 

Thanks for the reply Pommie, I think you are right about the lengths of variables. I went ahead and changed that section, do you think it's okay now?

I think that your advice on how to use C convention is great, but that is moreover a preference of the user. It's good you posted it so that others may view that suggestion.

Feel free to post anymore advice or comments!
 

That method is also interesting, and I think it offers an easy understanding of the purpose of variable, defines, or function names. The alphabetic organization is nice to have, especially in long code.
 
EN0 said:
This thread focuses on naming or defining variables appropriately when you program code. This is commonly viewed as an unimportant aspect that we reluctantly do just to get on with our program.
At times when I give examples I sometimes use short and even meaningless variable names. In part because I am lazy and in part because it helps move the illustration along.

I hope you have not taken this to mean that I think variable names are unimportant. Some say that naming is the most difficult and most important part of programming. I agree.

My naming is not always as consistent as it should be. I favor the conventions as indicated by mike but prefer to reverse the order as suggested by RB, then lcdInit() and lcdWrite() appear as a group in sorted lists like we see in IDE's like VS and now MPLAB X.

I only use underscores in #defined macros and constants, QUEUE_MAX

What rules you choose are less important then remaing consistent.

If you are working on existing code do not inject your style when it conflicts with the flavor of the code.
 
Last edited:
Some IDEs will automatically match case if they recognize the Variable, so I like a mixture of upper and lower case, for example, Write_LCD.

When I'm typing, I type it all in lower case, and if the case doesn't shift to match, I've got a typo in the name.

If I type "write_lcd", Write_LCD appears on my screen. If I type "writelcd" by mistake, it won't be capitalized and I'll notice the error immediately.

Visual Basic and Swordfish work this way.
 
At times when I give examples I sometimes use short and even meaningless variable names. In part because I am lazy and in part because it helps move the illustration along.

Yes, I understand, and that's exactly what the quote implicates.

I hope you have not taken this to mean that I think variable names are unimportant. Some say that naming is the most difficult and most important part of programming. I agree.

Certainly not. I think that many people perform the same technique while programming, but it will serve you better in the long run if the names of your variables are reputable. I have had difficulty thinking of what to name my variables, but as you continue to assign straightforward names, it becomes habitual which makes it easier.

What rules you choose are less important then remaing consistent.

That's a good concept to acknowledge, although, maintaining your rules is part of keeping consistency in your code.

If you are working on existing code do not inject your style when it conflicts with the flavor of the code.

Perhaps the "flavor" of the code, as you say, might possibly be distasteful on several occasions? If that is ever ensued, which it eventually will some time or another, then I disagree with your statement. True, you might have to painstakingly revise your code to achieve a more delectable flavor, but I think it would be worth it considering future debugging or help. I think the flavor of your code, in terms of formatting style, should not only be based on your preference but as the preference of others in case you might need to be taught a lesson or two.
 

I think that is okay to implement, but you don't want to have the same variable names except with different capitalization; that would confuse you in the future and others.
 
I think that is okay to implement, but you don't want to have the same variable names except with different capitalization; that would confuse you in the future and others.

That would confuse me in the present!

I like the instant feedback that the capitalization gives that the variable name is recognized. Long ago I used a BASIC that didn't implement variable checking. I typo'd the name of the variable that compensated for sensitivity variations, which was discovered about a 6" stack of graphs was printed!
 
Consistent naming conventions reduce the complexity of the programming process. You do not have to remember if you used writeLCD() or lcdWrite(). That is a good thing.


The code will not always be YOUR code. I was thinking about the case in which one is working on existing code.

As a professional, if you are asked to work on an existing program it is generally a bad idea to rename all the variables. Variables you introduce should follow the conventions of the exiting program to keep it consistent. In general it is up to the original author to set the tone. We should respect it.

Some workplaces/shops have strict style conventions. This makes sense in that everyone is used to that style and that shouldimprove productivity.

Working in an environment where each programmer is free to choose their style has pros and cons. One down side is that after working on code in several different styles it can be less easy to remain consistent when written new code.
 
The code will not always be YOUR code. I was thinking about the case in which one is working on existing code.

I misunderstood you.


I would agree with that, you might regret renaming them. Even though they might not seem to have any significance at the moment, usually professional programmers choose those names for a reason, and that reason might become clear later on. I think it would be good practice to at least comment the variable, indicating its purpose.

Some workplaces/shops have strict style conventions. This makes sense in that everyone is used to that style and that shouldimprove productivity.

Yes, I can see that. However, sometimes being unique in your style isn't such a bad thing either. Maybe you could find a better method or technique of accomplishing something.

Working in an environment where each programmer is free to choose their style has pros and cons. One down side is that after working on code in several different styles it can be less easy to remain consistent when written new code.

Yes, I think that might be true, but I think we all affix ourselves to one particular method that we find appealing. Perhaps that's because it's a little easier or because the style seems more effective. On some occasions, though, you might not have a choice. The obvious solution would be to practice as much as you can with all the styles, so it's just like learning another language.
 
Once I worked on project where I needed to design a library for all sorts of 2D geometry. One function I wrote was:

Code:
/**
 * Calculates the squared length of a vector v1.
 *
 * @param[in]  *v1  The vector of interest.
 *
 * @return  double  The squared length of the vector.
 */
double vc2d_sqrabs(const struct vector2d *v1);

This turned out to be very confusing function name for some programmers in the team. Some thought it calculated a "square root of the length of the vector".

I prefer using very short variable names in short math functions. Like the "v1" above. Makes the math easier to read. The implementation of the function was:

Code:
double
vc2d_sqrabs(const struct vector2d *v1)
/* Computes and returns the squared length of a vector v1. */
{
	/* TODO: Better error handling */
	assert(v1 != NULL);
	
	return (v1->x)*(v1->x) + (v1->y)*(v1->y);
}
 
Last edited:
Hi misterT,

Yes, I would prefer shorter variables when it comes to math as well. You might want to add some comments which indicate what the variables yield, otherwise I think most people can figure that out quickly.
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…