From: Robert Klemme Date: 2003-05-27T17:05:58+09:00 Subject: Re: Constant Definitions and Hiding "Julian Snitow" schrieb im Newsbeitrag news:pan.2003.05.27.06.19.59.938412@yahoo.com... > On Mon, 26 May 2003 21:58:48 +0200, Robert wrote: > > > > > Hi, > > > > we had a discussion on #irc the minute before and I'm thinking that there > > ought to be a warning in this situation: > > > > class Foo > > BAR = "bar" > > > > def print_it > > p BAR > > end > > end > > > > class Bar < Foo > > def print_it > > p BAR > > end > > end > > > > Foo.new.print_it > > Bar.new.print_it > > > > class Bar < Foo > > # next line should IMHO issue a warning > > # because of the hidden constant Foo::BAR > > BAR = "foo" > > end > > > > Foo.new.print_it > > Bar.new.print_it > > > > Output: > > > > "bar" > > "bar" > > "bar" > > "foo" > > > > This code does not warn (at least with 1.6.8) either with or without -w. > > > > What do others think? > > > > robert > > Perhaps using constants inside a class is what ought to be warned. > > class Foo > def bar > "bar" > end > def print_it > p bar > end > end > > class Bar < Foo > def bar > "foo" > end > end > > In a language that lets you do such beautiful, fluid things with > functions, the C++ mindset can only hold you back. ;-) What C++ mindset? I'm doing Java for a living... :-)) > If you must distrust the programmer so much, you can either make bar a > class method ( def Foo.bar ), and def print_it; p Foo.bar; end, or, if > going the constant route, refer to Foo::BAR explicitly. If you don't > specify that you only want the BAR defined in class Foo, and not some > subclass's idea of BAR, then the example you posted shows the correct > behavior on the part of the ruby interpreter. Of course the interpreter is right (he always is, isn't he? :-)), but I find this a bit surprising. Maybe this is not too big a problem, since the maintainer / writer of the sub class is likely the same person introducing the constant; but then, often one adds something later and old code breaks. > Remember the line, "A computer never does what you want it to do; only what you > tell it."? No amount of warnings will change that. :-) :-) Hm, maybe it's a question of expectations. OTOH I found it surprising that defining a singleton method that had been defined as a singleton method issues a warning, too. But I can see, that it's reasonable to warn about this. Regards robert