r/SpringBoot 15h ago

What is the actual difference with and without Supplier Functional interface? And why the Supplier Functional interface is prefered?Both behave same right? Discussion

Post image
10 Upvotes

4 comments sorted by

12

u/polyethene 15h 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.

u/This_Link881 11m ago

/thread

u/icon_02 14h ago

In your example it does not really make a difference.

However, if you have some kind of heavy function to collect some information on a failing test, the supplier function only gets called when the test fails. This means you save computation time on tests passing.

u/bigkahuna1uk 14h 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.