lundi 30 mars 2015

Substituting multiple Strings in String

I know there are a lot of questions and answers related to similar questions but I couldn't find an answer to my question. This a small snippet of my code:



private String substitute(String text) {
List<Macro> macros = getMacros();

for (Macro macro : macros) {
text = StringUtils.replace(text, macro.getKey(), macro.getValue());
}
return text;
}



  1. Would this be a good way to substitute multiple macros variables in a text String? This creates a new String object on every loop so I am wondering if there's a better way to do this. Ideally I would have used Apache Commons StrSubstitutor class but I can't because of the format of the tokens/macros (different formats and not between a fixed prefix/suffix). I also don't want to use Regex because of performance issues.


  2. According to some coding rules at work I need to mark the argument as final. I wonder if that's indeed good practice here. I know that Strings are immutable and I know that whenever I call StringUtils.replace() it will return me a new String object. But I am wondering if the String argument here should be marked as final as suggested and in the method do something like this:



    String result = text;
    for (Macro macro : macros) {
    result = StringUtils.replace(result, macro.getKey(), macro.getValue());
    }


    I just don't like this.




Any help would be appreciated. Thanks.


Aucun commentaire:

Enregistrer un commentaire