Is using “is” to name Boolean variables bad practice?

爷,独闯天下 提交于 2019-12-04 15:07:12

问题


Is naming Booleans that start with "is" bad practice now? My manager believes that "isAnything" is outdated and poor practice. Is this true?

myManager.isLame ? correct() : incorrect();

回答1:


It's used quite often in a lot of languages, but I don't know if it can be said with certainty that it's the preferred method.

I think consistency and everyone on a given team using the same standards/styles is the important thing to bear in mind.




回答2:


I would not use any hard and fast rules here. Although I find a prefix such as 'Is' useful in identifying a boolean property, there are many cases where 'Is' would not be the best choice.

  • Car.HasFlatTyre vs Car.IsFlatTyre
  • Cars.AreAllRed vs Cars.IsAllRed
  • etc...

The MSDN naming guidelines include the following relevant advice.

Do name Boolean properties with an affirmative phrase (CanSeek instead of CantSeek). Optionally, you can also prefix Boolean properties with Is, Can, or Has, but only where it adds value.




回答3:


isLame() is very common, and I consider it to be not lame. In Java, it's part of the JavaBeans specification, and therefore quite an ensconced practice.




回答4:


It's a matter of style, and I've seen it your way lots of times (and do this myself in many languages).




回答5:


Stylistically, my vote would be for hasValue or isNullOrEmpty. Using clever shortcuts or one-line if statements like that, however, is universally bad. It drastically reduces code readability and in most languages will not lead to any performance gain.




回答6:


it would be better if you create boolean variable with clear name

boolean lame;

and make method to check its value

isLame(){
  return lame;
}

It's generally better approach to invoke method over direct access to variable.




回答7:


Follow a language's documented convention. If there is no convention:

Omit type info in variable naming altogether.

That includes is for booleans.

boss.lame ? limp() : sprint()

For languages with strong typing the information is redundant.

For languages without strong typing the information is still redundant because IDEs and all of the various tools available now help with typing without having to convolute the names.

is is a verb. is_lame() should be an accessor method that returns a boolean value.



来源:https://stackoverflow.com/questions/6950841/is-using-is-to-name-boolean-variables-bad-practice

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