A practice that doesn’t make me cry
About a month ago, Doug posted a list of 10 MATLAB code practices that make him cry. (Not a pretty sight, I promise you.) One of the bad practices was using the name of a MATLAB function as a variable name or the name of your own function.
This caught my eye because I've seen this advice often given, and yet I so often ignore it. Specifically, I never worry about whether one of my variable names is the same as some MATLAB or toolbox function; I'm perfectly happy to name a variable diff, for example. And yet it never causes me trouble. In fact, you're supposed to be able to do this without trouble in MATLAB and many other programming languages; scoping and binding rules are designed to make this sort of thing work. Doug's post and some of the subsequent comments, though, reminded me that people, including experienced MATLAB users, do often report being tripped up by this. It made me start to wonder if I'm doing something different than those who run into variable name / function name confusion.
After thinking about it a bit I formulated a hypothesis. Most of my work with MATLAB involves writing functions. I don't often write scripts, except when I'm writing something for the blog or preparing a demo presentation. And my functions are generally quite short and do just one thing. (That's a habit I learned the hard way—by having to maintain code that I wrote 15 years ago.)
Variables inside a function exist only during execution of the function; they are automatically cleaned up and disappear when the function finishes and returns to the caller. Function variables simply have no effect on anything outside the execution of that function.
It's different if most of your MATLAB workflow involves repeatedly writing and running scripts. Any variable created inside a script that you run from the MATLAB prompt hangs around in the base workspace forever, unless you clear it or quit MATLAB. I can imagine that if you're doing that all day, having scripts that create variables with the same name as common functions could definitely cause puzzling problems.
You could run a script that makes a variable called diff, then move on to some data analysis and plotting steps, then go off to lunch, then come back in the middle of the afternoon and run a different script that tries to call the function diff, and boom, it doesn't work. MATLAB thinks you're trying to index into the variable diff, which you forgot you even made.
What do you think of my hypothesis? If you've been burned by naming a variable the same name as a function, was it in a scenario when you were writing and running scripts?
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.