Path: csiph.com!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: v_borchert@despammed.com (Volker Borchert) Newsgroups: comp.lang.java.programmer Subject: Re: How to handle same sanity checks Date: 22 Jun 2017 18:33:15 GMT Organization: Private site at Eddersheim, Germany Lines: 61 Distribution: world Message-ID: References: <87o9tgo0a9.fsf@munus.decebal.nl> X-Trace: individual.net 3Pumc/2VrhtzhQN0wyq5wADxVuEPp7wqoHEEvCrUMFJSujnTna Cancel-Lock: sha1:eJQqk6dAWtk09aiZrSG4lCqe1rs= Xref: csiph.com comp.lang.java.programmer:36700 Eric Sosman wrote: > On 6/22/2017 5:10 AM, 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? > > Tastes surely vary, but for repetitive checks I favor writing > the private internal helper method. Yes, the caller of doItPlease() > gets an exception originating from internalSanityCheck() instead, but > that shouldn't bother anyone. doItPlease() will be in the stack > trace anyhow, even though it's not at the very top. That can be a problem with some more-or-less-broken logging frameworks, and a nuisance if trying to diagnose over the phone. You can always do something like final InvalidParameterException e = new InvalidParameterException(String.format(ERROR_N, n)); final StackTraceElement[] s = e.getStackTrace(); e.setStackTrace(Arrays.copyOfRange(s, 1, s.length)); throw e; or even public class Throwables { private Throwables() { } public static T relocate(final T t, final int n) { final StackTraceElement[] s = t.getStackTrace(); if (n < s.length) { t.setStackTrace(Arrays.copyOfRange(s, n, s.length)); } return t; } } and then throw Throwables.relocate(new InvalidParameterException(...)), 1); -- "I'm a doctor, not a mechanic." Dr Leonard McCoy "I'm a mechanic, not a doctor." Volker Borchert