Make it possible to treat objects as falsy in order to make NullObjects more convenient
NullObject is quite a useful pattern. But refactoring from conditionals to null-object can be very painful because an instance of NullObject will be treated as truthy so code
... if obj can change its behavior. It'd be great to treat such objects as falsy. Most simple and consistent solution is to make method like #to_boolean or may be #__to_bool (not to break compatibility) which returns false for NilClass and FalseClass and true otherwise unless redefined.
I don't know whether perfomance impact'll be high or no.
It's one of a few things which cannot be reimplemented using ruby itself, so there is no possibility to construct a gem as a PoC
#1 Updated by Charles Nutter almost 2 years ago
I think you might have submitted this before, but I'd like to enter my strong opposition to this.
- It most definitely would affect performance. Any language construct that needs to check for truthiness would suddenly have to do a method call rather than simply an identity check.
- I think it is a terrible thing that other languages like Python and PHP make it possible for the same object to be true one moment and false the next (e.g. a list that empties out or a string that is blanked). What is true should always be true; what is false should always be false.
The last point is my really strong position. I do not think it should ever be possible for the contents of an object to define its truthiness, and by extension for changes to the contents of an object to change its truthiness.
#2 Updated by Rodrigo Rosenfeld Rosas almost 2 years ago
I should agree with Charles although I understand Ilya's concerns. Maybe another attempt to get this implemented would be simply requesting native support for a NullObject class in such a way that falsey would be either false, nil or an instance of NullObject. What do you think about such proposal?
#3 Updated by Charles Nutter almost 2 years ago
@rosenfeld That would certainly be less impact, but not zero-impact. I do not have a strong opinion one way or the other on that sort of change, but I still suspect it's unlikely to be approved. Changing the semantics of truthiness is a pretty major thing.
#4 Updated by Ilya Vorontsov almost 2 years ago
I understand your oppositions. IMO, NullObject should be a kind of immutable/singleton object so that object couldn't change its truthiness unless method is redefined. (but in ruby there're already many ways to shoot own leg)
It sounds reasonable. But it makes impossible to make EmptyList as a subclass of List.