Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!news.albasani.net!.POSTED!not-for-mail From: Lew Newsgroups: comp.lang.java.programmer Subject: Re: About using assertion Date: Thu, 19 May 2011 08:46:39 -0400 Organization: albasani.net Lines: 54 Message-ID: References: <92r0e9F6lvU1@mid.individual.net> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit X-Trace: news.albasani.net PXsIiJaHC45rFBSH1TFPyLiqwSoPt98vng1EefHQ/mr5zHsS0j/csOvNPu3snOAwhni9KZCMAJI6Za9RUwnR7YeRBkWWKS4q7/7Yom0P8an9s8hrn8IkEg/twrbM5hiI NNTP-Posting-Date: Thu, 19 May 2011 12:46:10 +0000 (UTC) Injection-Info: news.albasani.net; logging-data="pVwWH7WRShhHHAdq4kUH/Z0NAQNlOCkliYfGBY+gVwS35M4wuyoqH/ENfHKgAfWN1+AyeD1tdsefsFfeRBZjt96szH52+BkKk3hFscx8DogfmtOnE67FVUBV8sdd/szT"; mail-complaints-to="abuse@albasani.net" User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.17) Gecko/20110424 Thunderbird/3.1.10 In-Reply-To: Cancel-Lock: sha1:gar7da1Eloib1wz+qq/5ORYrWfM= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:4290 On 05/19/2011 02:34 AM, Michal Kleczek wrote: > Tim McDaniel wrote: > >> In article<92r0e9F6lvU1@mid.individual.net>, >> Robert Klemme wrote: >>> On 09.05.2011 18:11, Lew wrote: >>>> public class Foo >>>> { >>>> public double sqrt( double arg ) >>>> { >>>> if ( arg< 0.0 ) >>>> { >>>> throw new IllegalArgumentException( >>>> "sqrt(): negative argument "+ arg ); >>>> } >>>> assert arg>= 0.0; // precondition >>>> >>>> double result; >>>> // rest of algorithm ... >>>> return result; >>>> } >>>> } >>> >>> Lew, I am not sure what you tried to convey with this posting. I for my >>> part would say that the assert is a tad too much here since the if >>> clause before that gives me enough "confidence" that arg is actually>= >>> 0 at that line. If it isn't then I have bigger problems than >>> calculating square roots of negative numbers. :-) >> >> Consider >> >> Foo.sqrt(Double.NaN) >> >> The "if" fails, but if assertions are enabled, the "assert" catches >> it. This might be an illustration that an assertion can be useful >> even if you have "confidence" that it could never fire. >> >> (As a tangent, I'm not sure whether "Foo.sqrt(-0.0)" should throw an >> exception or not.) >> > > What a great example of why assertions are usefull - even if they look > redundant and not needed. > Thank You. That is wrong. That needs to be checked with an 'if' if 'NaN' is not a legitimate input. 'assert' is not meant to correct things, only to make sure that the correction is documented and proven. If 'assert' is turned off in production, you still have the bug if you use 'assert' as the only guard. -- Lew Honi soit qui mal y pense. http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg