Warning: I can’t think up something practical about what I prefer and explain below! Don’t say I didn’t warn you!
Last week I found myself writing a method ending with a question mark, but it wasn’t returning a Boolean. Just as most of the other methods ending with a question mark I wrote the last couple of years it returns either a NilClass instance, which evaluates to false, or some other object instance, which evaluates to true.
The question I want to answer is if such a method should return true or false or is returning nil or some object good enough?
Personally I think it should return a boolean value. I have more arguments opposed to returning a bool than not, but it just feels right, seems more logical. But! if there are humongous performance implications, I’m also happy enough with the way I did it before.
To check just this I wrote a simple class and some benchmarking code to see how big the implications are. I have two methods which mimics the normal situation and a method which returns a boolean value. I’m using the ‘!!’ trick to accomplish the typecasting. [you can see all the code in my ruby study git repos]
The test results show, I’m running the code 1 million times, that the difference is marginal. So for me the only logical conclusion is that returning a boolean, which feels more logical to me, is perfectly acceptable and will be my weapon of choice starting as of right now. If you have a practical use to actually justify this, please let me know!