"Bill Atkins" <dejaspam / batkins.com> schrieb im Newsbeitrag
news:e6056acc.0403090356.7654b195 / posting.google.com...
> Is there any way to require that all variables and class attributes be
> predeclared?  I'm looking for something similar to Perl's strict
> pragma.  It would prevent bugs like this:
>
> class Demo
>     def initialize
>         @count = 0
>     end
>
>     def anotherfunc
>         @cout += 1
>     end
>
>     def get_count
>         @count
>     end
> end
>
> d = Demo.new
> puts d.get_count
> d.anotherfunc
> d.get_count
>
> Note the typo in anotherfunc.  This code was intended to output a zero
> followed by a one, but because of the typo, will output two 0's.

Well, you get at least this:

irb(main):017:0> d.anotherfunc
NoMethodError: undefined method `+' for nil:NilClass
        from (irb):7:in `anotherfunc'
        from (irb):17
irb(main):018:0> d.get_count
=> 0
irb(main):019:0>

Isn't that verbose enough?

> Is there any way to prevent errors like this from happening?  I find
> it hard to believe that a language as well-designed as Ruby would lack
> this simple feature.

Alternatively you can do this:

class Demo
    attr_accessor :count
    private :count=

    def initialize
        self.count = 0
    end

    def anotherfunc
        self.cout += 1
    end
end

Which some would regard cleaner OO anyway.  This yields

irb(main):034:0> d.anotherfunc
NoMethodError: undefined method `cout' for #<Demo:0x1018f550 @count=0>
        from (irb):27:in `anotherfunc'
        from (irb):34
        from :0

Btw: If you have a well designed unit test, either error will show up
during testing.

Regards

    robert