This is another question about my new programming hobby, but it’s probably more of a matter of taste (and hence IMHO material) than Factual. Suppose I define a function foo(), which does something to a variable. Since variable names in functions are local in scope, I can give that parameter any name I want, even a name that is used for another variable in another function. But suppose that, as it happens, foo() will only ever be called on one particular variable, which is named x in the main program - I simply outsourced parts of the code to a separate function for structure and readability. Is it then good style to also call that parameter x in the definition of foo(), or should I give it a different name because it’s a different function? Since my programs are rather small and trivial (and nobody besides me will ever run them or work on the code), I suppose it doesn’t make much of a difference for me, but I guess while I’m at it writing code I might as well get used to good practices.
In general, you want to make things as “readable” as possible. So in answer to your question, I would not use the parameter name in foo() as the same as the variable you are using in main. (It really depends on what main is doing, but I might question the use of “x” as a variable name).
The more you program/code, the more you will find that that one function you thought would only ever be used 1) by one caller, and 2) in one application, ends up being re-used/re-purposed down the road. So the more generic/readable your parameter names are, the easier/clearer it will be down the road if/when you find you will want to re-use it.
I use sName_arg as the function argument. That way it’s clear where this variable came from and its scope.
Yes, I do something similar, along the lines of fctnsource.var.
Thirded (my habit has been to prefix the name with p_ to identify it as a parameter).
I would say to use in the function the name that makes most sense in the function, and use in the main the name that makes most sense in the main. If it happens that those two names are the same, then so be it, but don’t expect them to be.
Yes, the variables should be named based on their context.
Let’s say you have a function which controls a light intensity. You pass it a number from 1-255, and it sets the light intensity accordingly.
void setLightIntensity(int intensityStrength)
{
lightIntensity = intensityStrength;
}
Now, you have another function which gets the temperature, which you want to pass to the light intensity function so the light gets brighter or darket based on temp.
int getTemperature(void)
{
int temperature;
temperature=(temperature Getting Code)
return temperature;
}
Now your main function might look something like this:
void main
{
int outdoorTemperature=getTemperature();
setLightIntensity(outdoortemperature):
}
No need to name the variable the same at all, and in fact it would be confusing - especially since you might want to use the setLightIntensity() function to work with other variables like pressure or humidity or game ranking or whatever. So it shouldn’t know or care about the names of the variables in the calling function.
Now, let’s say I want to massage the temperature value to make it 1-255 from range of say -20 to +40. Now I am doing something to temperature explicitly for the setLightIntensity function. NOW I would give it a name that’s indicative of that context:
void main
{
int outdoorTemperature=getTemperature();
int temperatureIntensity=ConvertTemperatureToIntensity(outdoorTemperature);
setLightIntensity(temperatureIntensity):
}
The variables should always be descriptive and make sense basedmon the context they are being used in. Avoid shortening names unpess they are really unwieldy. I would rather read long variable names than guess at what the variables are. A lot of programmers would write thenabove like this:
void main
{
int ot=getTemp();
int ti=ConvTemp(ot);
setLI(ti):
}
It looks more ‘compact’, but it compiles to the same thing and is impossible to know what’s going on without inspecting the functions being called. This would be a big fail if I code reviewed it.
While I’m rambling about coding conventikns, don’t forget comments, and make them good comments. I can’t count the number of times I’ve seen ‘commented’ code like this:
//main function
void main
{
//get the temperature
int outdoorTemperature=getTemperature();
//convert the temperature
int temperatureIntensity=ConvertTemperatureToIntensity(outdoorTemperature);
//Set intensity of the light based on temperature
setLightIntensity(temperatureIntensity):
}
Those comments are useless. Comments should explain WHY you are dojng somethjng so that other people can follow the logic. These are better:
void main
{
// get raw temperature in range from -20 to +40 C
int outdoorTemperature=getTemperature();
// Convert raw temperature to normalized 0-255 needed for light intensity function
int temperatureIntensity=ConvertTemperatureToIntensity(outdoorTemperature);
setLightIntensity(temperatureIntensity):
}
on edit: sorry for losing the indenting
Some programming scenarios come to mind. One of them is FORTH, which has a great deal of flexibility in naming functions (well, “words”, but in effect functions). You can name a function “2”, for example, and define it to return 3, then when you add 2 to something it gets larger by 3. I remember somebody proposing examples of why you might want to do this, but it hardly goes along with cormac262’s wise counsel about making things readable. I always thought it would be fun to try writing as unreadable a program as I could while still making it functional, and one of the tricks would be to give every function a 20 character long name that was a randomly ordered series of lowercase L, and pipe, and numeral 1, characters.
At the opposite end of the spectrum is STAR-CCM+, a multiphysics package for numerical simulation, in which I’m doing lots of computational fluid dynamics work these last couple years. Arguably, you configure it, you don’t really program it. But you can create functions and variables, and also a bunch of other things that get named, such as sketches, extrusions, merges, cuts, lofts (all familiar to solid modeling folks), and also physics continua, solid bodies, tessellated volumes, addressable parts, spatial regions, mesh operations, reports, monitors, XY plots, contour plots, and on and on and on. Within a context such as contour plots or sketches or physics continua, each name must be unique. But for many contexts, you might have an entry referring to the same conceptual thing – for an air intake, for example, you could have a sketch, a body, a part, a region, a continuum, a monitor, and a plot. It keeps things simpler to use the same name for ALL of these different kinds of things that refer to the air intake. So far I haven’t hit a situation where this is not allowed, where it causes unhappy behavior, or where I get confused as a result, as the structure of the working environment makes the context clear at all times.
It probably doesn’t matter much, for for clarity, if you have a function that (say) calculates the volume of a sphere, it’s slightly preferable to call the local variable “r”, and use a variable like r_earth when you call the function to minimize the chance of confusion. I may have picked this up from doing mathematical calculations, where people tend to be punctilious about (say) integrating the function f(r) from R to infinity where “r” is the variable radius and R is a specific radius.
To avoid that in the future, surround your code blocks with code fences. Put ``` both above and below the code block, each on its own line. You can even indicate the language on the top one, e.g.
```javascript
console.log('hello world');
```
becomes
console.log('hello world');
And if you wonder how I put the backticks inside the codeblock, you can quote my post. It may help you understand why it’s called “code fencing.”
Does nobody put ‘in’ in front of parameters and ‘out’ in front of returned values?
Generally, the point of a function is to take a common operation and make it more generic. Therefore, the variable and parameter names should reflect this. To play off Sam Stone’s examples, one might have:
double convertCelsiusToFahrenheit(double temperatureCelsius)
{
return (9.0 * temperatureCelsius / 5.0) + 32.0;
}
But then the usage might be:
double indoorTemperature = getIndoorTemperatureCelsius();
printf("%f F", convertCelsiusToFahrenheit(indoorTemperature));
The function works on any temperature (in Celsius), whether indoor, outdoor, or inside a blast furnace. But the calling routine may well know the nature of the temperature, and if so it should be labeled that way.
Functions should generally be as generic as possible, and make the minimum number of assumptions about how they will be used. But when a function is used in a specific way, then the names should indicate that.
For the most part I also agree that variable names should be long and descriptive. But to be honest, I’d just write “convertCelsiusToFahrenheit(double t)” above. The function easily fits on a screen and it’s obvious that it operates on a temperature. Only if I had to further distinguish things, or if the function were complicated enough that it was hard to keep track of all the variables, would I switch to long names.
This. So much this. We no longer live in a world where longer variable names have actual memory implications. Use meaningful names.
… until you take up that piece of code months / years later and try to recall what you were thinking back when you wrote it.
The future you will bless the current one for this.
+1. Nearly all code is read far more often than it is written. So a little extra writing time than makes your code even slightly easier to read is a big win.
One neat thing we have at work is you can put comments next to an argument in a function call site like:
auto foo = bar(/*baz=*/true);
And there is a linter that will then warn you if the name of the argument is not baz. Handy if there are multiple parameters of the same type and you want to be sure that you’re passing to the right one, and also makes it so a reader doesn’t have to look back to the declaration to figure out what is being set to “true” or whatever.
‘out’ is a keyword in C#, used to denote a variable passed by reference, while the ‘in’ parameter denotes passing by value. ‘in’ parameters cannot be modified by the called function, and ‘out’ parameters can.
Thanks folks. There is some really good advice here!
I will now!
I mean in the variable name, not as a separate keyword. I’m used to this in C++
void foo(int inChannel, float inFrequency, float& outApproximateSignalToNoiseFound)
Then when you see a big code blob in that foo func and notice ‘inChannel’, you know that you’re looking at a function param that was passed in because of the ‘in’ prefix.
I’ll use descriptive names, but I don’t want them to be so long that they get easy to mistype. I’d probably name the function tempCtoF, and use variables like tempF and tempC internally. If I’m worried the name isn’t clear, I can use comments, where typos and misspellings won’t matter.
function tempCtoF (tempC) { //convert from Fahrenheit to Celsius
return tempC * 9/5 + 32;
}
If I use the word “Fahrenheit” in the name, I’m almost certainly going to wind up typing “Farenheit” at one point or something. Heck, I actually wrote “Celcius” above, originally.
Also, in nearly all cases, all of my function parameters are inputs, and output using return rather than modifying in place. I guess I could get mixed up which variables were inputs and which ones are internal to the function, though. I’ll have to consider if that’s something I want to indicate.
I’m also not remotely a professional programmer, though. There’s a reason why my example above is in vanilla JavaScript.