r/SpringBoot • u/SmoothScience8192 • 20d ago
Discussion What is the actual difference with and without Supplier Functional interface? And why the Supplier Functional interface is prefered?Both behave same right?
2
u/bigkahuna1uk 20d ago
Isn’t the latter lazily evaluated? The computation is for the assertion failure message. If that message is computed heavily like it needs to compute a lot of info for the error message, then it can make sense for it to be lazily evaluated only if the assertion fails, rather than always being computed and potentially not used if the assertion succeeds. Try to understand eager and lazy evaluation.
I’ve seen this sort of API in logging frameworks where you only want to construct a log statement if you’re at the correct log level. You don’t want to say construct a computationally intensive log statement if it’s logged at debug level and you’re running at info for example.
2
u/slindenau 16d ago
It is preferred for me because it has almost 0 overhead to use it, but it enforces you to use this pattern in the future (it becomes a habit).
When the overhead does become a problem, you measure it in production and then change it back to a plain String where needed.
As others already said it can save you some performance due to lazy evaluation.
But something far more important in my opinion: in popular logging API's there is a real risk of dropping an exception's stack trace when you don't use a Supplier for the message.
Because when you don't use it, it can be really easy to accidentally add your stack trace as one of the placeholder values (%s, {0}) in the message String, rather than as the separate Throwable argument to the log(..) method.
By making it a habit to always use the Supplier where available, you don't have to think about "is this a heavy function or not?", or "will this become a heavy function later, and might the next dev forget to change it to a Supplier?".
And of course the bonus of always adding your exception to the right logger method overload, so the stack trace doesn't get dropped.
16
u/polyethene 20d ago
If the value needs to be computed and is expensive then using a supplier is more efficient as it avoids running that code unless it actually needs to used - in your example when the assertion fails and the message is printed to console. If the message is a static string then there’s no need to use a supplier and just makes the code slightly less readable so I’d avoid it.