× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How to avoid code duplication doing input validation in subclass

Xaver Kapeller
May 22, 2015
<p>I suggest you split your method into two separate method, one public method which you implement in your base class and a protected abstract method which is called by the other method and which is implemented in the sub classes. </p> <p>This way you can implement things which apply to all subclasses in the base class and avoid code duplication. The resulting base class would look something like this:</p> <pre><code>public abstract class AbstractConfig { public String doStuff(List&lt;Params&gt; params) { if (performErrorChecks()) { return doTheActualStuff(params); } return null; } protected abstract String doTheActualStuff(List&lt;Params&gt; params); } </code></pre> <p>And the subclasses would just implement <code>doTheActualStuff()</code>:</p> <pre><code>public class CustomConfig extends AbstractConfig { @Override protected String doTheActualStuff(List&lt;Params&gt; params) { ... } } </code></pre> <p>You can also declare <code>doStuff()</code> as <code>final</code> in <code>AbstractConfig</code>. This would additionally prevent any subclass from overriding <code>doStuff()</code> and accidentally replacing your common error checking.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/30380321/How%20to%20avoid%20code%20duplication%20doing%20input%20validation%20in%20subclass/30380558">Stack Overflow</a>.</p>
comments powered by Disqus