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

非 Y 不嫁゛ 提交于 2019-12-08 15:41:36

问题


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?


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



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




回答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.




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


来源:https://stackoverflow.com/questions/3160261/whats-a-good-naming-convention-for-methods-that-take-conditional-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!