Feature #8273
closed
Make it possible to treat objects as falsy in order to make NullObjects more convenient
Added by prijutme4ty (Ilya Vorontsov) over 11 years ago.
Updated almost 3 years ago.
Description
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
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.
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?
@rosenfeld (Rodrigo Rosenfeld Rosas) 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.
@headius (Charles Nutter)
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)
@rosenfeld (Rodrigo Rosenfeld Rosas)
It sounds reasonable. But it makes impossible to make EmptyList as a subclass of List.
- Status changed from Open to Rejected
Rejected for the same reason as #6180.
Matz.
- Project changed from 14 to Ruby master
Also available in: Atom
PDF
Like0
Like0Like0Like0Like0Like0Like0