Please, consider these functions:
f[x_] := Module[{},
Return[x + 1];
];
g[x_] := Module[{},
Return[x - 1];
];
I want evaluate doSomething
each time f (or g) is invoked. The obvious way
f[x_] := Module[{},
doSomething;
Return[x + 1];
];
g[x_] := Module[{},
doSomething;
Return[x - 1];
];
presents a serious drawback, because it delivers on the programmer's shoulders the responsibility to add the required command inside each function. Little it may seems, in large projects it's a major source of (my...) , hard to trace back, oversights. Leaving aside metaprogramming, is it possible escape from this boilerplate code by means of a function whenInvoked[{f,g,...} , doSomething]
?
Addendum
I'm not "looking to alter the definition of a function", let's sayf
, although I acknowledge that such an error can be carried out using the hypothetical function when
, mentioned above. I'm looking for a practical way to log the calls to f
. As I see the topic, the maintenance of the log is a task of the program that makes use of f
, not of f
itself, mainly because it can be accomplished in many ways. To dictate any modality to f
, simply invalidate its portability.
Clear[whenInvoked]; SetAttributes[whenInvoked, HoldAll]; whenInvoked[t : {__}] := (dosomthing; t)
? $\endgroup$