Note that there are some explanatory texts on larger screens.

plurals
  1. POComposite Strategy pattern - java - How bad is this code?
    primarykey
    data
    text
    <p>This question is kind of continuation to my earlier post: <a href="https://stackoverflow.com/questions/944824/visitor-pattern-implementation-in-java-how-does-this-look">Visitor pattern implementation in java- How does this look?</a></p> <p>I got a bit confused while refactoring my code. I am trying to convert my visitor pattern (explained in the prior post) into a composite strategy pattern. I am trying to do something like this:</p> <pre><code>public interface Rule { public List&lt;ValidatonError&gt; check(Validatable validatable); } </code></pre> <p>Now, I would define a Rule like this:</p> <pre><code>public class ValidCountryRule { public List&lt;ValidationError&gt; check(Validatable validatable) { // invokeDAO and do something, if violation met // add to a list of ValidationErrors. // return the list. } } </code></pre> <p>Now, I could have two different types objects to be validated. These two could be completely different: Say I have a Store that is <code>Validatable</code>, and then a <code>Schedule</code> which is <code>Validatable</code>. Now, if I would write a composite that would look like this:</p> <pre><code>class Validator implements Rule { private List&lt;Rule&gt; tests = new ArrayList&lt;Rule&gt;(); public void addRule(Rule rule) { tests.add(rule); } public List&lt;ValidationError&gt; check(Visitable visitable) { List&lt;ValidationError&gt; list = new ArrayList&lt;ValidationError&gt;(); for(Rule rule : tests) { list.addAll(rule.check(visitable); } } public Validator(ValidatorType type) { this.tests = type.getRules(); } } </code></pre> <p>I would define an <code>enum</code> that defines what set of checks go where...</p> <pre><code>public Enum ValidatorType { public abstract List&lt;Rule&gt; getRules(); STORE_VALIDATOR { public List&lt;Rule&gt; getRules() { List&lt;Rule&gt; rules = new ArrayList&lt;Rule&gt;(); rules.add(new ValidCountryRule()); rules.add(new ValidXYZRule()); } // more validators } </code></pre> <p>and finally, I would use it like this:</p> <pre><code>Validator validator = new Validator(ValidatorType.STORE_VALIDATOR); for (Store store : stores) { validator.check(store); } </code></pre> <p>I have a strange feeling that my design is flawed. I am not liking the idea that my Rule interface expects a <code>Validatable</code>. Could you please suggest how I would improve this?</p> <p>Appreciate your help.</p>
    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.
 

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