23

What is a good way to name a method that checks if X needs to be done, and does X it if necessary?

For example, how to name a method that updates a user list if new users have logged in? UpdateListIfNeeded seems too long, while simple UpdateList implies a possibly expensive and unnecessary operation is done every time. EnsureListUpdated is a variant as well.

C# has a bool TryXXX(args, out result) pattern (e.g. int.TryParse(str, out num)) to check if X is possible and do it, but that is subtly different.

  • 1
    Just a point of recommendation, methods like this, while well intentioned, should be created with caution. Along the way they tend to get peppered into unrelated code under the guise of "just in case" or "adding a call to it in X() fixed a bug, but I'm not sure why". If you have the discipline to only call RefreshUserList() during LoginUser() and LogoutUser(), and not during, say GetUser() (where the list should be up-to-date already), then by all means the advice below applies. – Kevin McCormick Aug 21 '12 at 18:44
25

I tend to use Ensure. It carries the meaning of making sure that something is taken care of, however that needs to be done. If it's already fine, just check it and we're done. Otherwise, do it. Either way, just ensure that it gets done.

13

My preference is UpdateList. If nothing needs to be done, so be it. The expense should always be minimized anyway, so if UpdateList is doing more than necessary something is incorrect in its implementation.

Basically it's the verb that tells you what the method should do. CalculateX should always recalculate X. GetY should always return Y, but only do the work of retrieving it if necessary. Likewise, UpdateZ requests an update of Z assuming it's done the most efficient way possible.

1

Call me "Maybe"

Co-opted from Haskell snippets I've seen, try

UpdateListMaybe();
  • 2
    I suppose if I understood Haskell better, this might make more sense. Corollary: If this is used in a language other than Haskell, it will only be understood by those who know Haskell. – Robert Harvey Aug 21 '12 at 17:59
  • 2
    Six years later, I am a different programmer, with slightly more knowledge of Haskell things. I no longer endorse this answer, haha. I guess my idea at the time was to use the word "maybe" to signify that the function handles some sort of optionality. I still do that sometimes (e.g. Option[A] => B is called maybeToB) – Mark Canlas Jul 18 '18 at 14:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.