From: AdSR Date: 2006-12-30T19:00:05+09:00 Subject: Re: Methods validating their arguments: good or bad? Vincent Fourmond wrote: > Michael Judge wrote: > > What do you think? Do you usually validate your arguments? > > I usually don't, first because I find it makes the code less readable, > and second because of the performance loss. What I would like, however, > is something Eifel-like: > > def method(a) > entry_check > a.is_a(String) > begin > # now do something with code > exit_check > # a test on exit > end > > And the possibility to simply turn it off, that is, completely skip > over the entry_check and exit_check blocks. > > What do you think ? I think that it would be a marvellous addition to > Ruby. Of course, that doesn't stop you from writing Test::Units, that > would be somehow orthogonal. > > Cheers, > > Vince What you could do is create a subclass with checking, something like this (untested): class Unchecked def method(a) # do your stuff end end class Checked < Unchecked def method(a) # do pre-ckecking result = super.method(a) # do post-checking result end end Depending on whether you're testing or running in production you'd switch the actual class used. If you use this pattern a lot, maybe you could create some general decorator class (using method_missing etc.) that would allow you to specify tests for each decorated class or object. Just a hint. Cheers, AdSR