What is the proper approach to functions that have side-effects in Delphi/Pascal?
For example, I could have a boolean function
DeleteFile that returns
True if the file was deleted and
False otherwise. How do I collect the return value?
1) The very explicit form would be:
if DeleteFile(MyFilePath) then begin IsMyFileDeleted := True; end; else begin IsMyFileDeleted := False; end;
2) Less bulky would be:
IsMyFileDeleted := False; if DeleteFile(MyFilePath) then begin IsMyFileDeleted := True; end;
3) Or even shorter, but discouraged by JEDI - perhaps it is acceptable just to collect return values:
IsMyFileDeleted := False; if DeleteFile(MyFilePath) then IsMyFileDeleted := True;
My problem with 2 and 3 is that I explicitly state something (
X := False) that I may not know for sure.
4) I would rather not set the variable beforehand and have its value completely determined by the function:
IsMyFileDeleted := DeleteFile(MyFilePath);
Here the issue is that it is a bit misleading, because assigning a value to a boolean has a pretty serious side-effect. I'm not sure if this usage is desirable.
Some argue that functions should never have side-effects, but I think some of Pascals internal functions violate that.
5) The alternative would be making it procedures with a result variable to be filled by the procedure:
That might go against the trend to keep parameter use to a minimum (Clean Code).
4 and 5 would be the only ways to collect a return value other than boolean, I suppose? Does that mean anything for boolean functions?
Yes, there are many ways to do the same thing and maybe I'm just worried about nothing really, but I'm trying to develop a good style and I wonder if there are any best practices. For a beginner, many principles seem to be in conflict all the time.