Boolean method naming readability

2019-01-30 20:58发布

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

public boolean isUserExist(...)

or:

public boolean doesUserExist(...)

or:

public boolean userExists(...)

11条回答
Bombasti
2楼-- · 2019-01-30 21:06

The goal for readability should always be to write code the closest possible to natural language. So in this case, userExists seems the best choice. Using the prefix "is" may nonetheless be right in another situations, for example isProcessingComplete.

查看更多
We Are One
3楼-- · 2019-01-30 21:18
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

查看更多
神经病院院长
4楼-- · 2019-01-30 21:22

Purely subjective.

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

if ( userExists( ... ) )

or

while ( userExists( ... ) )
查看更多
Lonely孤独者°
5楼-- · 2019-01-30 21:24

I would go with userExists() because 1) it makes sense in natural language, and 2) it follows the conventions of the APIs I have seen.

To see if it make sense in natural language, read it out loud. "If user exists" sounds more like a valid English phrase than "if is user exists" or "if does user exist". "If the user exists" would be better, but "the" is probably superfluous in a method name.

To see whether a file exists in Java SE 6, you would use File.exists(). This looks like it will be the same in version 7. C# uses the same convention, as do Python and Ruby. Hopefully, this is a diverse enough collection to call this a language-agnostic answer. Generally, I would side with naming methods in keeping with your language's API.

查看更多
霸刀☆藐视天下
6楼-- · 2019-01-30 21:25

I like any of these:

userExists(...)
isUserNameTaken(...)
User.exists(...)
User.lookup(...) != null
查看更多
来,给爷笑一个
7楼-- · 2019-01-30 21:27

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.

查看更多
登录 后发表回答