Why not raise an exception? from Ryo Furue on 2001-08-15 at 12:51:00: > Hi there, > > How do you report the failure of object creation, that is, if you find > it impossible to properly initialize the object in the "initialize" > method? Raising an exception is clearly an option. But, what if the > "failure" is a normal part of the flow of the program? as in > > class SomeClass > def initialize(file) > line = file.gets > if line > # initialize instance vars according to "line" > else > return nil ##<- a fictious Ruby feature > end > end > end > > a = Array.new > f = File.open("datafile", "r") > loop { > s = SomeClass.new(f) > if ! s then break end > a.push(s) > } > a.each { .... > > I've used a fictious feature that the method "initialize" can return > nil to indicate the failure of creation. I think this would be > elegant. > > An alternative is that you define an instance method which indicates > whether the object is in a normal state or not: > > class SomeClass > def ok? > @ok > end > end > > f = File.open("datafile", "r") > s = SomeClass.new(f) > if (s.ok?) ... > > This works, but some programmer might use the name "ok?", others might > use "good?", yet others "integrity_conserved?",... In C++, there is a > convention that you overload the "not" operator (!) for the class to > do the job, so that you can very often say > > SomeClass s(f); > if (!s) {... > > Is there such a convention in the Ruby community? Is it feasible to > implement my fictious feature mentioned earlier? I'd appreciate any > comments. > > Thank you, > Ryo