Tutorial :What's a good naming convention for methods that take conditional action?



Question:

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?


Solution:1

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()  


Solution:2

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.)


Solution:3

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.


Solution:4

Michael Petrotta's answer (IfNecessary or IfRequired suffix) is good, but I prefer a shorter alternative: IfNeeded.

ElevatePermissionsIfNeeded()  

And if you want something even shorter I would consider a prefix like May or Might:

MayElevatePermissions()  MightElevatePermissions()  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »