言語内DSLには、流れるようなインタフェースがいいじゃん、
みたいに言われてたので、試しに文字列操作APIを少し書いてみた。
public class Strings { protected StringBuilder builder; public Strings(String str) { this.builder = new StringBuilder(str.length()); this.builder.append(str); } public String execute() { return new String(this.builder); } public Strings replaceAll(String from, String to) { int index = 0; while ((index = this.builder.indexOf(from)) != -1) { this.builder.replace(index, index + from.length(), to); } return this; } public Strings removeBy(String str) { int index = this.builder.indexOf(str); if (index == -1) { return this; } this.builder.delete(0, index + str.length()); return this; } public Strings removeUntil(String str) { int index = this.builder.indexOf(str); if (index == -1) { return this; } this.builder.delete(0, index); return this; } public Strings append(String str) { this.builder.append(str); return this; } public Strings insertHead(String str) { this.builder.insert(0, str); return this; } }
使い方は
String str = new Strings("aaabbbcccddd") .replaceAll("c", "x") .removeBy("bb") .insertHead("hoge") .execute();
で「hogebxxxddd」が得られる。
Stringクラス自体、流れるように書くことはできるけど
拡張したい時には(まさかStringをextendsするわけにはいかないから)
こんなユーティリティを作ると良いのかな。