Why use this syntax?

1 回表示 (過去 30 日間)
David
David 2014 年 12 月 3 日
コメント済み: David 2014 年 12 月 3 日
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?

採用された回答

Adam
Adam 2014 年 12 月 3 日
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 件のコメント
David
David 2014 年 12 月 3 日
Hm, I will start doing that way. I'm sure I will benefit from it. Thanks

サインインしてコメントする。

その他の回答 (1 件)

Guillaume
Guillaume 2014 年 12 月 3 日
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.

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

タグ

タグが未入力です。

製品

Community Treasure Hunt

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

Start Hunting!

Translated by