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.
2
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.
1
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.
Call me “Maybe”
Co-opted from Haskell snippets I’ve seen, try
UpdateListMaybe();
2