views:

45

answers:

4

Let's say I have a method, Foo(). There are only certain times when Foo() is appropriate, as determined by the method ShouldFooNow(). However, there are many times when the program must consider if Foo() is appropriate at this time. So instead of writing:

if ShouldFooNow():
   Foo()

everywhere, I just make that into one function:

def __name():
    if ShouldFooNow():
       Foo()

What would be a good name for this method? I'm having a hard time coming up with a good convention. IfNecessaryFoo() is awkward, particularly if Foo() has a longer name. DoFooIfShould()? Even more awkward.

What would be a better name style?

A: 

MaybeFoo() or PossiblyFoo()

Amber
That makes the functions sound nondeterministic.
mikerobi
A: 

You could use EnsureFoo().

For example, the method EnsurePermissions() will take the appropriate action if needed. If the permissions are already correct, the method won't do anything.

Niels van der Rest
+2  A: 

I think you're pretty close. Put the action/intent at the head of the method name, for easier alphabetic searching. If I were writing something like that, I'd consider

FooIfNecessary()
FooIfRequired()

Say, for instance,

ElevatePermissionsIfNecessary()
Michael Petrotta
A: 

I've recently started using the convention:

FooIf(args, bool);

Where args are any arguments that the method takes and bool is either expecting a boolean value or a Func of some kind that resolves to a boolean. Then, within that method, I check the bool and run the logic. Keeps such assertions down to one line and looks clean to me.

Example in my C# code for logging:

public void WarnIf<T>(T value, string message, Func<T, bool> isTrue)
{
  if (isTrue(value)) _log.Warn(message);
}

Then I would call it with something like:

WarnIf(someObject, "This is a warning message to be logged.", s => s.SomeCondition == true);

(That caller may not be correct, but you get the idea... I don't have the code in front of me right now.)

David
Is that really how you would call `WarnIf()?` Wheres's the first arg?
Rosarch
Edited. I missed that one in a hurry. Got too used to the extension methods I've been writing all day :)
David