Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Replace Validatable by a generic type parameter T to make the validation framework type safe.</p> <pre><code>public interface Rule&lt;T&gt; { public List&lt;ValidationError&gt; check(T value); } </code></pre> <p>Let's extend our framework with an interface ValidationStrategy:</p> <pre><code>public interface ValidationStrategy&lt;T&gt; { public List&lt;Rule&lt;? super T&gt;&gt; getRules(); } </code></pre> <p>We are dealing with rules bounded by "? super T" so we can add a rule for Animal to a Dog Validator (assuming Dog extends Animal). The Validator now looks like this:</p> <pre><code>public class Validator&lt;T&gt; implements Rule&lt;T&gt; { private List&lt;Rule&lt;? super T&gt;&gt; tests = new ArrayList&lt;Rule&lt;? super T&gt;&gt;(); public Validator(ValidationStrategy&lt;T&gt; type) { this.tests = type.getRules(); } public void addRule(Rule&lt;? super T&gt; rule) { tests.add(rule); } public List&lt;ValidationError&gt; check(T value) { List&lt;ValidationError&gt; list = new ArrayList&lt;ValidationError&gt;(); for (Rule&lt;? super T&gt; rule : tests) { list.addAll(rule.check(value)); } return list; } } </code></pre> <p>Now we can implement a sample DogValidationStrategy like this:</p> <pre><code>public class DogValidationStrategy implements ValidationStrategy&lt;Dog&gt; { public List&lt;Rule&lt;? super Dog&gt;&gt; getRules() { List&lt;Rule&lt;? super Dog&gt;&gt; rules = new ArrayList&lt;Rule&lt;? super Dog&gt;&gt;(); rules.add(new Rule&lt;Dog&gt;() { public List&lt;ValidationError&gt; check(Dog dog) { // dog check... return Collections.emptyList(); } }); rules.add(new Rule&lt;Animal&gt;() { public List&lt;ValidationError&gt; check(Animal animal) { // animal check... return Collections.emptyList(); } }); return rules; } } </code></pre> <p>Or, like in your sample, we may have an Enum providing several dog validation strategies:</p> <pre><code>public enum DogValidationType implements ValidationStrategy&lt;Dog&gt; { STRATEGY_1 { public List&lt;Rule&lt;? super Dog&gt;&gt; getRules() { // answer rules... } }, // more dog validation strategies } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload