In ruby, is truthiness idiomatic for a method name ending with a question mark?

后端 未结 4 1971
情深已故
情深已故 2021-02-13 21:33

Is it normal for methods with a question mark to return something that\'s truthy (for example, a number) to indicate that something is true, or should true itself b

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-13 22:29

    There are two answers to your question, and both are valid:

    Technically, anything returning a false or nil value acts as a false boolean when doing a conditional test, just as a non-nil or true value acts as a true. So, the method in question will work correctly for most times you'd want to know if something is an integer.

    But stylistically a method that ends with '?' should return either a Boolean true or false and only those.

    The method in question doesn't really play nicely with our expectations and fails the POLS ("principle of least surprise") because you can reasonably expect a Boolean value being returned, and get an integer or a nil. THAT could lead to unpleasant surprises in code when it fails with an unexpected nil or a Fixnum value.

    So, while it's a valid method, it's not a good method, and I would have brought it up in a code review. And that leads to a separate discussion of how subtle things like that can enhance or hurt code maintenance, but that's an entirely different discussion.

提交回复
热议问题