Path: csiph.com!x330-a1.tempe.blueboxinc.net!aioe.org!news.swapon.de!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Robert Klemme Newsgroups: comp.lang.java.programmer Subject: Re: About using assertion Date: Mon, 09 May 2011 22:17:11 +0200 Lines: 52 Message-ID: <92r0e9F6lvU1@mid.individual.net> References: <09cb7d90-9b79-473e-9869-4476c5a0191a@w24g2000yqb.googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net W4O8UjVtv6z1mOt/m8WpnQD4TDh8w1vgRFLtyCnKXTOoP1HZY= Cancel-Lock: sha1:aTGHKZzMv4rRRiDi66xuTupvkRk= User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2.17) Gecko/20110414 Lightning/1.0b2 Thunderbird/3.1.10 In-Reply-To: X-Antivirus: avast! (VPS 110509-1, 09.05.2011), Outbound message X-Antivirus-Status: Clean Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:3875 On 09.05.2011 18:11, Lew wrote: > Roedy Green wrote: >> Robert Klemme wrote, quoted or indirectly quoted someone who said : >>> Having said that I'd say that argument checking is probably more >>> important than assertions. > >> Assertions should not be used to validate user-provided data. They >> need to be in effect all the time. Assertions about detecting bugs in >> the program, mis use of a method. >> >> Assertions, even though they hide it he body of method, are >> documentation on just what sorts of thing the method can do. >> in a simple case, you might assert that a SQRT method can only handle >> non-negative numbers. > > > 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. :-) It's probably a different story if the calculation is done by a private method in which case I'd probably add the assert to the beginning of that method just to be sure the caller (which can only be in the same class or nested classes) did not make a mistake. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/