Why use this syntax?

1 view (last 30 days)
David
David on 3 Dec 2014
Commented: David on 3 Dec 2014
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?

Accepted Answer

Adam
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.
  1 Comment
David
David on 3 Dec 2014
Hm, I will start doing that way. I'm sure I will benefit from it. Thanks

Sign in to comment.

More Answers (1)

Guillaume
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.

Categories

Find more on Programming in Help Center and File Exchange

Tags

No tags entered yet.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!