I stumble across this case somewhat often, and I'm surprised about finding so few similar discussions around the web. This question is very related, but my problem is that I want a method that does the more general "do X if Y" rather than "do X if needed". The answer in that link is to use the prefix Ensure, but that word does not fit if ensuring X is not the method's intention.
The scenario I have in mind is this:
void mayPerformAction() { // Do some preparatory calculations // ... if (shouldPerform) { // Perform action // ... } } The reason I am not using two separate methods (shouldPerformAction() and performAction()) is because both the condition and the action depend on some preparatory calculations, which would have to be repeated otherwise. Now, my question is: what is the most logical and readable name for the method mayPerformAction()?
To clarify, it is important to the caller that the action may sometimes not be executed, otherwise it seems logical to me to use performAction().
I admit that this is kind of an XY-problem, and there are multiple solutions posted, each of which have good arguments for and against them. To summarize:
- Abstract away the doubt and give it a less detailed name, e.g. just
performAction(). - Prefer clarity and do the calculations twice; the performance difference will be negligible in many cases anyway:
if (shouldPerform()) performAction(). - Same as above, but store the shared result of the calculations in a global variable or return it (I prefer the latter) so no resources are wasted.
I feel like the best approach depends on how 'serious' the condition is and how expensive the preparatory calculations are; as such I'm leaving the question unanswered for now.
EnsureBufferFilled().ensuremethods myself. Heck I've written method names withifin them. But I'll take a good abstraction over either if i can find one. Sadly I can't always find one. If I can't, well, I'll take yourensureoverifXthenY()any day. :)...IfRequired(...)in addition toEnsure...(...)when there's no good alternative but the fact something won't necessarily happen needs to be explicit.