Path: csiph.com!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Robert Klemme Newsgroups: comp.lang.java.programmer Subject: Re: How to handle same sanity checks Date: Sun, 25 Jun 2017 12:31:14 +0200 Lines: 45 Message-ID: References: <87o9tgo0a9.fsf@munus.decebal.nl> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net DZXJX9BK2twabKCqx3pBRw0sELC+kp4RDcZVVvyZ3fCKCKqF4= Cancel-Lock: sha1:ZznFqZOiKoq2CkOoFOitQYwZ980= User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Thunderbird/52.1.1 In-Reply-To: <87o9tgo0a9.fsf@munus.decebal.nl> Content-Language: en-GB Xref: csiph.com comp.lang.java.programmer:36720 On 22.06.2017 11:10, Cecil Westerhof wrote: > In my code I have several methods that start with: > if ((n < MIN_VAL) || (n > MAX_VAL)) { > throw new InvalidParameterException(String.format(ERROR_N, n)); > } > > That is not really DRY. A few minor remarks: brackets around comparisons are not needed. Is this really part of JCA code? If not I would just use IllegalArgumentException to not give a false impression. > I could write a method like: > private void checkN(n) { > if ((n < MIN_VAL) || (n > MAX_VAL)) { > throw new InvalidParameterException(String.format(ERROR_N, n)); > } > } > > And then replace all the checks with a call to checkN. But then the > exception is generated in the method checkN instead of the method that > has a wrong parameter. > What is the best way to handle this? I would not worry about the stack too much (see other subthreads of this discussion). Going through all the hassle of removing an entry just to let the stack trace end up one level up is way too much effort here. After all, we are talking about a RuntimeException that is intended to catch a programmer error, likely during testing. In that context there is usually no issue having logging switched on to a level of verbosity to see the stack trace. I would suggest another name for the method though, more along the lines of ensureArgumentIsInRange(final int n). A "check" can be anything and result in anything (ask yourself "what is the result of the check?") but what you really want here is that processing only continues if the values are within the range. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/