FAQ
overflow

Great Answers to
Questions About Everything

QUESTION

I am working on a small custom Markup script in Java that converts a Markdown/Wiki style markup into HTML.

The below works, but as I add more Markup I can see it becoming unwieldy and hard to maintain. Is there is a better, more elegant, way to do something similar?

private String processString(String t) {
    t = setBoldItal(t);
    t = setBold(t);
    t = setItal(t);
    t = setUnderline(t);
    t = setHeadings(t);
    t = setImages(t);
    t = setOutLinks(t);
    t = setLocalLink(t);

    return t;
}

And on top of it, passing in the string itself and setting it back to the same string just doesn't feel right. But, I just don't know of any other way to go about this.

{ asked by CZap7 }

ANSWER

You could create a StringProcessor interface:

public interface StringProcessor {

    String process(String input);
}


public class BoldProcessor implements StringProcessor {

    public String process(final String input) {
        ...
    }
}

and create a List from the available implementations:

final List<StringProcessor> processors = new ArrayList<StringProcessor>();
processors.add(new ItalicProcessor());
processors.add(new BoldProcessor());
...

and use it:

String result = input;  
for (final StringProcessor processor: processors) {
    result = processor.process(result);
}
return result;

{ answered by palacsint }
Tweet