Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Martin Gregorie Newsgroups: comp.lang.java.programmer Subject: Re: How to handle same sanity checks Date: Thu, 22 Jun 2017 10:27:18 -0000 (UTC) Organization: A noiseless patient Spider Lines: 41 Message-ID: References: <87o9tgo0a9.fsf@munus.decebal.nl> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Injection-Date: Thu, 22 Jun 2017 10:27:18 -0000 (UTC) Injection-Info: mx02.eternal-september.org; posting-host="0d3e354b6e02414e6d46f69c40af244f"; logging-data="4975"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18imvDhGTpMLlVgZrmdCYNcZBd8CK0Lf0s=" User-Agent: Pan/0.141 (Tarzan's Death; 168b179 git.gnome.org/pan2) Cancel-Lock: sha1:wNUEaekBjlaIeY/ZucFbmt75Sds= Xref: csiph.com comp.lang.java.programmer:36694 On Thu, 22 Jun 2017 11:10:38 +0200, 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. > > 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 agree that using such a method would tidy up the calling code, but if I used this type of method I'd generalise it to something like this: private void checkInRange(int n, int lowLimit, int highLimit, String error) { String format = "%s: %d is outside range %d - %d"; if ((n < lowLimit) || (n > highLimit)) throw new InvalidParameterException( String.format(format,error, n, lowLimit, highLimit)); } -- martin@ | Martin Gregorie gregorie. | Essex, UK org |