From: Alex Young <alex@...> Date: 2011-10-03T06:38:08+09:00 Subject: [ruby-core:39843] Re: [Ruby 1.9 - Feature #5372][Open] Promote blank? to a core protocol Eric Hodel wrote in post #1024462: > On Sep 27, 2011, at 6:52 PM, Alex Young wrote: > >> Think of it like the Null Object pattern in reverse. > > The Null Object is described on the C2 wiki and its related pages: > > http://c2.com/cgi/wiki?NullObject > > It seems to be better than implementing Object#empty? Where it's an option, yes, it's better, but in places where I call #null? or #empty? I don't necessarily have the flexibility to use it. Where I'm handed a return value by a method in some library, core, or a gem, or whatever, I've often got to make a type check of some sort before safely operating on it, and that check is frequently a check that the object is of a type that it makes sense to operate on. > Can you show me a description of the opposite? What I mean by "in reverse" is that with the Null Object, we have an instance which silently does the right thing. We don't have to care that it's null, we just call methods on it like we would on a non-Null instance. With a #null? or #blank? method, we instead have a way to ask each instance directly whether it's null, without having to care about its class. If it quacks like a null, then it's null. > >> Because the core API commonly returns nil in error cases.. > > Can you show some examples? I don't seem to write nil checks very often > when using core methods, but maybe I am forgetting. Having a quick look over the core docs, there's quite a few in File::Stat and Process::Status, all the try_convert() methods, Kernel.caller, Kernel.system, arguably String#slice and Regexp#match (although I can't see the latter being reasonably alterable), and Thread#status at least. > >> case thingy >> when Blank >> # catch-all >> # other cases >> end > > What about: > > case thingy > # other cases > else > # catch-all > end Yep, that's another way to do the same sort of thing, but with a Blank or Null it's more explicit and more flexible. With a bare "case...else..." you have to handle both correct nulls and erroneous values in the "else" clause. With Null, you can leave the "else" clause purely for handling the error case, where you've somehow got a response you weren't expecting. I think it's clearer. -- Alex -- Posted via http://www.ruby-forum.com/.