Bill Atkins
5/9/2005 12:53:00 AM
But Ruby already makes a distinction between nil and uninitialized. Compare:
b + 4
NameError: undefined local variable or method `b' for main:Object
with
b = nil; b + 4
NoMethodError: undefined method `+' for nil:NilClass
In my example, file is certainly initialized - it's just initialized
to nil. If create_new_log_file returns nil, file can't be considered
uninitialized.
On 5/8/05, John Carter <john.carter@tait.co.nz> wrote:
> On Mon, 9 May 2005, Bill Atkins wrote:
>
> > This isn't about changing programming habits. Having nil return nil
> > for missing methods can have serious consequences.
> >
> > Consider:
> >
> > file = create_new_log_file
> > file.log "here's a bit of information"
> >
> > You're expecting this code to log something to a file every time it
> > gets called. But suppose create_new_log_file returns nil, due to some
> > mistake you've made while coding it.
>
> You confirm what I am saying about the difference between "uninitialized
> and "no thing here". There should be an explicit difference.
>
> Such a mistake you have presented would typically fill "file" with
> "uninitialized", and invoking the log method on "uninitialized" should
> throw an exception.
>
> On the other hand, a nifty way of deliberately switching off logging,
> without changing a line of the client code would be to stuff "No thing
> here" into file, resulting in no thing happening.
>
> That is why I have now withdrawn my RCR, and are working instead on an
> implementation of the Nothing class, leaving "nil" to mean
> "uninitialized".
>
> It's coming along very nicely thank you, the only sorrow I have at the
> moment is to be able to do what I used to with nil takes a bit more
> typing....
>
> may_be_nothing = nil
>
> if may_be_nothing
> definitely_isnt_nothing( may_be_nothing)
> end
>
> now becomes...
>
> may_be_nothing = Nothing.new # I love that
> unless may_be_nothing.nothing?
> definitely_isnt_nothing( may_be_nothing)
> end
>
> ie. "nil" is a Special object in ruby, and the code for handling "if"
> statements knows about it. (The RTEST macro in ruby.h)
>
> But hopefully the change conditional to virtual method refactoring will
> make most of those instances go away.
>
> John Carter Phone : (64)(3) 358 6639
> Tait Electronics Fax : (64)(3) 359 4632
> PO Box 1645 Christchurch Email : john.carter@tait.co.nz
> New Zealand
>
> Surprisingly enough, this email does not originate from a beetle.
>
>
--
Bill Atkins