Why use this syntax?

1 visualización (últimos 30 días)
David
David el 3 de Dic. de 2014
Comentada: David el 3 de Dic. de 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?

Respuesta aceptada

Adam
Adam el 3 de Dic. de 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 comentario
David
David el 3 de Dic. de 2014
Hm, I will start doing that way. I'm sure I will benefit from it. Thanks

Iniciar sesión para comentar.

Más respuestas (1)

Guillaume
Guillaume el 3 de Dic. de 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.

Categorías

Más información sobre Get Started with MATLAB en Help Center y File Exchange.

Etiquetas

Aún no se han introducido etiquetas.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by