While the existing answers give good reasons why storing the value is best, they miss out on what I feel is an important one (in fact, the most important one): in your second example (running the function twice), you introduce a potential race condition.
If buildSet()
relies on outside factors (which is highly probable in any non-trivial function - and could become true with later changes), there is a chance that the value changes between the if
check and the second call. This could create a subtle and hard to find bug, which would potentially only become visible when you made changes elsewhere, or certain events happened with specific timings.
This is, by itself, a good reason to avoid such a pattern.