HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Better way to manipulate this string in sequence?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thismanipulatewaybettersequencestring

Problem

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.

Solution

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 processors = new ArrayList();
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;

Code Snippets

public interface StringProcessor {

    String process(String input);
}


public class BoldProcessor implements StringProcessor {

    public String process(final String input) {
        ...
    }
}
final List<StringProcessor> processors = new ArrayList<StringProcessor>();
processors.add(new ItalicProcessor());
processors.add(new BoldProcessor());
...
String result = input;  
for (final StringProcessor processor: processors) {
    result = processor.process(result);
}
return result;

Context

StackExchange Code Review Q#40746, answer score: 17

Revisions (0)

No revisions yet.