From: Robert Dober Date: 2006-08-07T00:17:29+09:00 Subject: Re: How to react on nil or wrong object-type as parameter ------=_Part_119914_4725452.1154877444141 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: quoted-printable Content-Disposition: inline On 8/6/06, Yochen Gutmann wrote: > > Hi, > > I was just wondering: how do I react on a method-invocation with a > nil-object instead of eg. String? How do I test it? And how can I assure > that it is the right kind of object? > > class AClass > def a_method aString > puts aString+aString > puts aString.reverse > end > > end > > an_object =3D AClass.new > an_object.a_method "hello" # works > an_object.a_method 3#-> undefined method > an_object.a_method nil #-> undefined method > > > Does Duck-Typing mean "ah, the programmer always knows, which kind of > objects this method expects. Thus never an error will occur."? This > seems very optimistic to me if not naiv. You cant just trust that the > any programmer who uses your class knows what exactly is happening in > your method and which type of object is required. > > Thankful for any hint. Well what a nice occasion. I have to reply fast because I will be outnumbered fast ;) I have for quite a while now spoken up for some mechanisms for defensive programming and early failure, without success so far. What you can do e.g. is def aMethod something raise WhateverException, "whatever info useful" unless String =3D=3D=3D something you might also distinguish sometimes between nil and other problems However I have to conceede a point to the ducktypers (which is quite a nice feature I never want to see disappear) *sometimes* you want something to reply to #reverse and to #+, ( a String object might not reply to these messages ). So you could just fail or fail with a more meaningful message like this raise GreatExplanation, "sage sayings" unless something.respond_to?:reve= rse I still think it would be great to have an expressive syntax about this lik= e e.g; def act actor : Actor def act actor is Actor def act actor where Actor =3D=3D=3D actor def act actor : SomeThing note that SomeThing could also be a module and ruby should check if the instance methods of SomeThing are replied to by actor. Thus just doing kind of an automated duck type check. Hope you do not mind using your thread for some lobbying :) Cheers Robert > Regards, > Yochen > > -- > Posted via http://www.ruby-forum.com/. > > --=20 Deux choses sont infinies : l'univers et la b=EAtise humaine ; en ce qui concerne l'univers, je n'en ai pas acquis la certitude absolue. - Albert Einstein ------=_Part_119914_4725452.1154877444141--