开发者

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

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

e开发者_如何转开发verywhere, 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?


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


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.


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


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


I don't see what's wrong with the original code:

if shouldFoo():
  Foo();

is perfectly clear IMHO.

Not just that, but it clearly separates concerns of deciding about doing the action, vs the action itself.

Another option for a similar question with a slightly different approach to avoiding the postfix:

https://softwareengineering.stackexchange.com/a/161754/262009

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜