How to name a method which may or may not perform an action depending on a condition

coding-standardslanguage-agnosticmethodsnaming

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.

Best Answer

You're trapped in a structural way of thinking. A name should abstract away implementation details. It shouldn't become a short hand for them.

 IfBirthdayBuyCake();

is a terrible name. It exposes implementation details as badly as if you wrote them here naked.

I would reach for a better name and a better abstraction.

celebrateHoliday();

Somewhere in it you'll likely find something like this

if ( birthday() ) {
    buyCake();
}

and maybe some other holidays. When you call it, it may do nothing at all. Which means when you call it you don't have to know if today is a holiday. That not-knowing frees you from that detail. That's what a good name should do.

If you'll forgive a longer name:

celebrateTodaysHoliday()

makes it a little clearer that if today has no holiday then this does nothing. This makes the scope of discussion explicit.