Search code examples
javacode-duplication

avoid code duplication


consider the following code:

if (matcher1.find()) {
   String str = line.substring(matcher1.start()+7,matcher1.end()-1);
   /*+7 and -1 indicate the prefix and suffix of the matcher... */    
   method1(str);
}
if (matcher2.find()) {
   String str = line.substring(matcher2.start()+8,matcher2.end()-1);
   method2(str);
}
...

I have n matchers, all matchers are independent (if one is true, it says nothing about the others...), for each matcher which is true - I am invoking a different method on the content it matched.
question: I do not like the code duplication nor the "magic numbers" in here, but I'm wondering if there is better way to do it...? (maybe Visitor Pattern?) any suggestions?


Solution

  • Create an abstract class, and add offset in subclass (with string processing too... depending of your requirement).

    Then populate them in a list and process the list.

    Here is a sample absract processor:

    public abstract class AbsractProcessor {
    
        public void find(Pattern pattern, String line) {
            Matcher matcher = p.matcher(line);
            if (matcher.find()) {
                process(line.substring(matcher.start() + getStartOffset(), matcher.end() - getEndOffset()));
            }
        }
    
        protected abstract int getStartOffset();
    
        protected abstract int getEndOffset();
    
        protected abstract void process(String str);
    
    }