More about variable names inside functions
Last week I wrote that I do not normally worry very much about whether a variable name inside a function I'm writing might be the same as the name of a function somewhere else. Unfortunately, I bungled my point so badly that some readers felt it necessary to make sure I understood the value of writing readable code. Hmph. Of course, I didn't help things by thoughtlessly choosing the MATLAB function diff as an example. It's quite unlikely that I would actually use diff as a variable; it was just the first function name that came to mind when I was writing my last post.
Let me try again, and this time I'll explicitly consider readability.
I've been using MATLAB for more than two decades, but I don't know all the functions in MATLAB. When I write a function, do I use which every time I name a variable in order to make sure there's no other function with that name? No, of course not. Who wants to program that way? And I don't need to, because MATLAB is like just about every other programming language in that it allows you to use a name locally even though someone might have used the same name somewhere else.
Also, users of my functions have probably written their own functions, and I can't possibly know what function names they have chosen. Fortunately, it doesn't matter because of the way variable name scoping rules work.
Without these scoping rules, we wouldn't even be able to safely choose readable variable names. The functions I have put into MATLAB and Image Processing Toolbox have been used by thousands (hundreds of thousands? millions?) of people. If I really had to be sure that the variable names in my functions did not conflict with any functions that those users had written, then I wouldn't be able to use readable variable names at all. I'd probably have to use variable names that look more like hash codes:
A_3858f62230ac3c915f300c664312c63f = eye(3);
If your normal working routine involves writing and running scripts, then I agree with the oft-given advice to be careful about choosing your variable names. In particular, don't use the names of common MATLAB functions.
But variables inside functions live a short, controlled life. Write compact functions with a minimum number of conditional branches, and choose your variable names to help the code reader as much as possible. And if the readable variable name you choose happens to have the same name as some other MATLAB function that's ever been written, or that will be written in the future, that's OK.
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.