Boolean method naming readability

后端 未结 12 702
南笙
南笙 2020-12-12 15:10

Simple question, from a readability standpoint, which method name do you prefer for a boolean method:

public boolean isUserExist(...)

or:

相关标签:
12条回答
  • 2020-12-12 15:46
    public boolean userExists(...)
    

    Would be my prefered. As it makes your conditional checks far more like natural english:

    if userExists ...
    

    But I guess there is no hard and fast rule - just be consistent

    0 讨论(0)
  • 2020-12-12 15:46

    My simple rule to this question is this:

    If the boolean method already HAS a verb, don't add one. Otherwise, consider it. Some examples:

    $user->exists()
    $user->loggedIn()
    $user->isGuest() // "is" added
    
    0 讨论(0)
  • 2020-12-12 15:49

    Method names serves for readability, only the ones fit into your whole code would be the best which most of the case it begins with conditions thus subjectPredicate follows natural sentence structure.

    0 讨论(0)
  • 2020-12-12 15:51

    I would say userExists, because 90% of the time my calling code will look like this:

    if userExists(...) {
      ...
    }
    

    and it reads very literally in English.

    if isUserExist and if doesUserExist seem redundant.

    0 讨论(0)
  • 2020-12-12 15:51

    In this particular case, the first example is such horrible English that it makes me wince.

    I'd probably go for number three because of how it sounds when reading it in if statements. "If user exists" sounds better than "If does user exists".

    This is assuming it's going to be to used in if statement tests of course...

    0 讨论(0)
  • 2020-12-12 15:52

    Purely subjective.

    I prefer userExists(...) because then statements like this read better:

    if ( userExists( ... ) )
    

    or

    while ( userExists( ... ) )
    
    0 讨论(0)
提交回复
热议问题