Path: csiph.com!x330-a1.tempe.blueboxinc.net!aioe.org!news-transit.tcx.org.uk!news.albasani.net!.POSTED!not-for-mail From: Lew Newsgroups: comp.lang.java.programmer Subject: Re: About using assertion Date: Mon, 09 May 2011 11:35:21 -0400 Organization: albasani.net Lines: 102 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit X-Trace: news.albasani.net bbJY36UC3XcAwO+Y9BQKPRZeAQmvl+6qKKyX7BJPd85GXyQsN7qG6KdByayVRAfR4sbcUDXmzeuw3xt9XX8R0w== NNTP-Posting-Date: Mon, 9 May 2011 15:35:19 +0000 (UTC) Injection-Info: news.albasani.net; logging-data="3nbUB00ylrPwq6yD83hovYa6lFMc+u0c+eDxcF+GLhYqolCNtDcRrk/rw/RCHTCHRyCo+0HVFdnF00Rqs8SGda/mCaP3uLQQDuXuP2G7QUkKAoADHOyjWJA6KVP6Crbj"; 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:mGrfV2pVCPVJYmob0BMGJvClH3w= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:3862 byhesed wrote: > I am reading a book about object-oriented design pattern. > The book, Object-Oriented Software Development Using Java 2/e by > Xiaoping Jia, says that... > >     Using assertions derived from the preconditions for all methods is > known as defensive programming. >     Its aim is to prevent a component from being misused. > >     Design Guideline: Use Assertions Aggressively > >     Each method should include assertions on the preconditions and > postconditions of the method and invariants of the class > > Do I have to always use assertion? > Is it better to use assertion? > > What's your idea? Assertions are an excellent tool for their purpose, much as a hammer is an excellent tool for its purpose. Either can be misused. A hammer is not a good tool to saw wood. Assertions are not a good tool to handle exceptions. Java's 'assert' is a keyword to support assertions, which are a wider computer-science concept. (Note that this differs from the JUnit 'Assert...()' family of methods.) Assertions document and enforce invariants, preconditions and postconditions. These are algorithmic concepts, applicable to all programming, not just object-oriented. Research them thoroughly. An invariant is something that must hold true if you follow the algorithm. It might be an invariant that an array index is valid, or that an attribute is not null. It's a precondition if the invariant holds prior to some action or transformation. It's a postcondition if the invariant holds just after some action or transformation. Exceptions are a tool, among others, that causes invariants to hold true. Assertions, i.e., Java 'assert' expressions, prove that that enforcement worked correctly. Succinctly: Exceptions enforce, assertions prove. Remember that assertions can be turned off at classload time. Exceptions cannot. For example, suppose you have a requirement that a particular attribute is never 'null'. You enforce that with a setter method using 'if' and exceptions. You prove that the enforcement worked using 'assert'. package com.lewscanon.eegee; import org.apache.log4j.Logger; public class Foo { private final transient Logger logger = Logger.getLogger( getClass() ); private Bar bar = new Bar(); public Bar getBar() { assert bar != null; // invariant return bar; } public void setBar( Bar newb ) { if ( newb == null ) { IllegalArgumentException exc = new IllegalArgumentException( "null Bar" ); logger.error( exc ); throw exc; } bar = newb; assert bar != null; // postcondition } Notice that assertions do NOT enforce rules for the argument to a 'public' method; they only demonstrate that code under the class's own control did its job. So the class's own code enforces that the argument is not 'null', then the 'assert' demonstrates that it worked. You realize that 'assert' cannot enforce arguments to public methods because it can be disabled. Assertions don't always have to be on, but the truth they prove should always be true. So exceptions (and ifs) always enforce, assertions sometimes prove. The JLS defines the 'assert' stuff here: This article gives good guidance for 'assert': This article describes the mechanics of Java's 'assert' mechanism, but not much about why or when you'd want to: You should be well-schooled in algorithmic invariants and assertions regardless of your platform. -- Lew Honi soit qui mal y pense. http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg