4 ms·
Rather than adding syntax for it, the sane approach would just be to generalize the functionality. T Log<T>(string msg, Func<T> func) { Log(msg);
by daeken 8y ago
Rather than adding syntax for it, the sane approach would just be to generalize the functionality.
T Log<T>(string msg, Func<T> func) {
Log(msg);
return func();
}
var result = operation switch {
"+" => Log("addition", () => a + b),
"-" => Log("subtraction", () => a - b),
"/" => Log("division", () => a / b),
_ => throw new NotSupportedException()
};
This is shorter, cleaner, and how most folks would actually write something like this, I imagine.
- quietbritishjim 8y agoI don't know a great deal of C#, but couldn't you just do: T Log<T>(string msg, T result) { Log(msg); return result; } var result = operation switch { "+" => Log("addition", a + b), "-" => Log("subtraction", a - b), "/" => Log("division", a / b), _ => throw new NotSupportedException() }; You already have a lambda for calling Log(), no need for a second to call the inner function. This does change the order of evaluation though. I just mention it for academic interest. To be honest, I find the idea of passing a parameter to Log() (whether it's the value or the function) that your don't actually want logged, so that you can shoehorn two statements into an expression, abhorrent. Just write the two statements out! I think an old-fashioned switch statement is the right tool here.
- daeken 8y agoI think the order of operations here is important. Take, for example, the case of operation == "/" and b == 0. You might find it valuable to log that you're doing a division, before it catches fire due to the divide by zero. Obviously a contrived example, but that was my thinking with the inner function. Either way, pretty straightforward.
- joel_ms 8y ago>To be honest, I find the idea of passing a parameter to Log() (whether it's the value or the function) that your don't actually want logged, so that you can shoehorn two statements into an expression, abhorrent. You've basically reimplemented Haskell's Debug.Trace[0] :) The difference is of course that Haskell doesn't really have statements in the same way that C# does, so in Haskell it's nescessary to turn the log/trace-function into an identity function after you've applied the message-string. I agree that it is ugly, and in any serious project I would use a proper logging setup, but I almost feel like the ugliness is a feature not a bug. It's like an extra cost when doing debug-by-print, which at least seem to keep me more mindful about cleaning up after myself. [0] http://hackage.haskell.org/package/base-4.12.0.0/docs/Debug-Trace.html#v:trace http://hackage.haskell.org/package/base-4.12.0.0/docs/Debug-...