Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Andreas Leitgeb Newsgroups: comp.lang.java.programmer Subject: Re: How to handle same sanity checks Date: Thu, 22 Jun 2017 11:26:36 -0000 (UTC) Organization: A noiseless patient Spider Lines: 41 Message-ID: References: <87o9tgo0a9.fsf@munus.decebal.nl> Reply-To: avl@logic.at Injection-Date: Thu, 22 Jun 2017 11:26:36 -0000 (UTC) Injection-Info: mx02.eternal-september.org; posting-host="9ecd988584fe5ba656dda35ed07d3df5"; logging-data="12221"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1826/BhA3aZlUbG6MsBqAk/" User-Agent: slrn/1.0.2 (Linux) Cancel-Lock: sha1:/Ygy7KQ2IJ/Bb09pGDemqP7DaaI= Xref: csiph.com comp.lang.java.programmer:36696 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. I would not worry about where the exception gets thrown from, as long as the call-stack includes the "real culprit". If you really want it thrown at the call-site, there are these slightly more verbose variants: Let checkN() *return* the exception (or null if all was ok), then: for (Exception e=checkN(...);e!=null;) { throw e; } Yes, it's weird to use a "for" here, but "if" doesn't allow ad-hoc declaration of the Exception var. If you declare "e" ahead, then it becomes: (not much better, imho) Exception e; if ((e=checkN(...))!=null) { throw e; } (You could also combine this with Martin Gregorie's suggestions.) Another approach is, to wrap creation of the exception and the check separately: private Exception invalPar(...) { return new InvalidParameterException(String.format( ... )); } private boolean checkN(...) { return ((n < MIN_VAL) || (n > MAX_VAL)); } and at call-site: if (checkN(...)) { throw invalPar(...); }