Philip inherited a large Java application. It was the sort of application that needed to solve a clear business problem, so the original programmer started by building his own “template engine”, to simplify the process of generating output.

A template engine needs a simple way to do string replacements, but unfortunately, Java doesn’t offer a String class with a variety of “replace” methods for different situations. No, this Architect had to invent this wheel, using nothing but used chewing gum and his own wits.

public class FunctionLibrary {

    public static String replaceAll(String input, String toRepalce,
            String replacement) {
        return StringUtil.replaceAll(input, toRepalce, replacement);
    }
}

Ah, the power of object orientation . Talk about adherence to the “single responsibility principle”! But wait, what does StringUtil do?

public class StringUtil {
  public static String replaceAll(String aReceiver, String anOldString, String aNewString) {
    int tmpIndex;
    int tmpLastIndex = 0;
    StringBuffer tmpResult;
    int tmpLength;

    if (null == aReceiver) {
      return null;
    }

    if ((null == anOldString) || (null == aNewString)) {
      return aReceiver;
    }

    tmpLength = anOldString.length();

    if (aReceiver.length() < 1) {
      if (tmpLength < 1) {
        return aNewString;
      }

      return "";
    }

    if (tmpLength < 1) {
      tmpResult = new StringBuffer();
      tmpResult.append(aNewString);
      tmpResult.append(aReceiver);

      return tmpResult.toString();
    }

    tmpIndex = aReceiver.indexOf(anOldString, 0);

    if (tmpIndex < 0) {
      return aReceiver;
    }

    tmpResult = new StringBuffer();

    while (tmpIndex > -1) {
      tmpResult.append(aReceiver.substring(tmpLastIndex, tmpIndex));
      tmpResult.append(aNewString);
      tmpIndex += tmpLength;
      tmpLastIndex = tmpIndex;

      tmpIndex = aReceiver.indexOf(anOldString, tmpIndex);
    }

    if (tmpLastIndex < aReceiver.length()) {
      tmpResult.append(aReceiver.substring(tmpLastIndex));
    }

    return tmpResult.toString();
  }
}
[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!