Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: null checks Date: Wed, 26 Jul 2017 16:40:19 -0400 Organization: A noiseless patient Spider Lines: 40 Message-ID: References: <70f5af57-8dc0-416c-b2aa-0bbbb47fc7b5@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Wed, 26 Jul 2017 20:36:19 -0000 (UTC) Injection-Info: mx02.eternal-september.org; posting-host="c1f748753cdb62fa720f6cbb99b07888"; logging-data="21587"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19XkJ2EHxr3epNXfYvgPZo9" User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Thunderbird/52.2.1 In-Reply-To: Content-Language: en-US Cancel-Lock: sha1:ITxKH8m4JCXH97FR+jiqbkkiq/8= Xref: csiph.com comp.lang.java.programmer:37002 On 7/26/2017 2:40 PM, Eric Douglas wrote: > [...] > Would this be a valid use of assert? > [A method asserts that it is running on the Event Dispatch Thread] "Bless you, it all depends!" -- Pitti-Sing Specifically, it depends on your attitude towards calling the method on an unsuitable thread: Would that be a "bug" or a "mistake?" If the call occurs on the wrong thread, is it because something has gone wrong in the program's logic ("bug"), or because the programmer was ignorant or perhaps careless ("mistake")? In the "bug" case an `assert' seems entirely appropriate, whereas for a "mistake" it would probably be better to throw something like an IllegalStateException. Bear in mind that `assert' can be disabled without recompiling, and is in fact disabled unless explicitly enabled at run-time. Thus it is more suited to a debugging situation than to a defensive one; you'd enable `assert' during testing and fix the bugs it highlights, then leave it "latent" in the code in case mysteries arise after deployment and you'd like to turn it back on again. But you would not use `assert' to check that a user's input is valid, or that a particular file is accessible, or anything else that is not already under the program's control. The code you link to lies in a gray area: You can debug your own use of it until you're satisfied all is well, but that's not the end of the tale. The code is a `protected' method of a `public' class, meaning that other programmers can extend the class and call the method -- and perhaps call it inappropriately. Your tests never saw their faulty code, and the `assert' is turned off until somebody thinks to turn it back on again, and ... In this case, a test that will *always* be there and *always* fire may be appropriate. This may be a case where IllegalStateException would be preferable. ... but then again, maybe not. "It all depends!" -- esosman@comcast-dot-net.invalid Twelve hundred seventy-four days to go.