From: Ben Giddings Date: 2005-05-05T03:49:30+09:00 Subject: Re: Typo-checking instead of static typing On Wednesday 04 May 2005 12:21, Joe Van Dyk wrote: > On 5/4/05, Jon A. Lambert wrote: > > Ben Giddings wrote: > > > > > > Static typing tends to find typos and brainos in code before it's > > > executed. > > > > > > > My most frequent Ruby error: > > "NoMethodError: undefined method `foo' for nil:NilClass" > > > > Not a typo, and arguably anything is a braino. > > > > Fixed by asking oneself two questions > > 1) How in sam hill did that get set to nil? > > 2) Can method bar can return nil, if blah blah foozle wimble? > > > > That's about my most common error too (it ties with a parse error due > to a missing 'end' statement). Python to the rescue! See, when your language doesn't have end statements you can't *possibly* have any of these types of problems, right? *grin* Ok, but seriously. We have "ruby -w" and "ruby -c" and "unit tests". So let's have an analogy. Someone writs the following bit of C code: int do_something(int foo) { int i; if (foo > 500) { printf("Whoa, %d is too many times! I can't do that!", fo); } else { for (i=0; i 500 puts "Whoa, #{fo} is too many times! I can't do that!" else foo.times { |i| puts i } end end do_something(ARGV[0]) "ruby -c" would say this is perfect syntax, which it is. So that's kinda useless for typos and brainos "ruby -w" would run it, and it would barf with this message: foo.rb:4:in `>': undefined method `>' for false:FalseClass (NoMethodError) from tmp/foo.rb:4:in `do_something' from tmp/foo.rb:11 The line number is useful, but the message sure isn't. It turns out that string > number complains about FalseClass. I dunno why. Anyhow, it's obvious there is *some* error, so presumably the programmer would remember to 'to_i' the arg to do_something(). Then there's the typo in the "puts" line. Until the person happens to try an arg greater than 500, they will have no indication the code has a flaw. Now, would a unit test catch this? If the programmer was careful, maybe. But maybe not. So, what advice would you guys give to a C programmer who wants a Ruby tool to look over lines of code he may rarely execute? Ben