Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Cecil Westerhof Newsgroups: comp.lang.java.programmer Subject: Re: How to handle same sanity checks Date: Thu, 22 Jun 2017 13:21:40 +0200 Organization: Decebal Computing Lines: 49 Message-ID: <87k244nu7v.fsf@munus.decebal.nl> References: <87o9tgo0a9.fsf@munus.decebal.nl> Mime-Version: 1.0 Content-Type: text/plain Injection-Info: mx02.eternal-september.org; posting-host="e57c15ed9d20cb5f0e1e910deb92a515"; logging-data="18026"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18I4rhK1GyujW4uMNLxrjMT2m1s7wFwvO4=" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/24.5 (gnu/linux) X-Homepage: http://www.decebal.nl/ Cancel-Lock: sha1:2t5a4C3emmuX9az+mRHdEXn3nW0= sha1:Nh4h+Sn3of3zQsn6/91eYXMYhsE= Xref: csiph.com comp.lang.java.programmer:36695 On Thursday 22 Jun 2017 12:27 CEST, Martin Gregorie wrote: > 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 OK, it is not a big no-no then. > 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)); > } There is only one range, but it is good to keep in mind for when that changes. -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof