33

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.

dbkk
  • 2,106
  • 17
  • 16
  • 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
  • 1
    similar question: https://stackoverflow.com/q/3160261/929164 – Daniel Dror Apr 06 '21 at 17:00

3 Answers3

33

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.

Mason Wheeler
  • 82,151
  • 24
  • 234
  • 309
  • 1
    i like this answer, in fact my code is full of `updateCounterIfNeeded` methods, `ensureCounterIsUpdated` sounds much much better. I will propose to stick to this convention to my team. – user193655 May 13 '22 at 09:53
16

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.

Matt S
  • 3,273
  • 15
  • 25
3

Call me "Maybe"

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

UpdateListMaybe();
Mark Canlas
  • 3,986
  • 1
  • 29
  • 36
  • 3
    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
  • 4
    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