Why use this syntax?
3 views (last 30 days)
Show older comments
Hello.
I'm quite new to programming in general, and I wonder if there is some logical reason to do the following.
When reading examples and descriptions of functions I often see:
fileName = 'blabla.txt';
newFile = fopen(fileName);
When I use fopen I type directly in the () instead of creating a variable holding the name, is there a good reason to do it as writen above?
Or is it simply good practice?
0 Comments
Accepted Answer
Adam
on 3 Dec 2014
Personally I find it good practice to do the above, especially if the same thing is being used more than once. This is especially true of numbers or booleans where I don't like so-called "magic numbers" or "magic bools".
If you just call a function as:
myFunc( 7, true, 5, false );
it carries no meaning, whereas named variables do.
In your specific example this is not so much the case, but I still prefer to do this. It also makes it easier if, for example the filename is going to come from a UI or some other source where it would naturally be in a variable.
More Answers (1)
Guillaume
on 3 Dec 2014
Most likely, the author plans to reuse filename later on in the code. For example:
filename = 'blabla.txt';
fid = fopen(filename, 'r');
if fid<1
fprintf('Failed to open %s\n', filename);
else
[a, count] = fread(fid, 2000, 'uint8');
if count ~= 2000
fprintf('%s was only %d bytes long\n', filename, count);
end
end
It also allows you to refactor easily later. For example you may decide that filename comes from a function.
If it's only one time use, there's no advantage.
0 Comments
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!