Step4:クラスに分割する
それではいよいよクラスの分割です。
まず、
たとえば、
このような
クラスを抽出した結果はリスト6、
public class XmlApiAction extends Action {
...
public ActionResult index() throws Exception {
List<Division> divs = diviisonService.getDivisions();
List<User> users = userService.getUsers();
// XmlBuilderをnewして使用する
XmlBuilder builder = new XmlBuilder(divs, users); ―①
Document doc = builder.buildDocument();
writeDocument(doc);
}
private void writeDocument(Document doc) {
...
}
// インナークラスで宣言!
private static class XmlBuilder {
private final List<Division> divs;
private final List<User> users;
private int index = 1; ―②
public XmlBuilder(List<Division> divs, List<User> users) { ┓
this.divs = divs; |
this.users = users; |
} ┛③
private Document buildDocument() throws Exception {
Document doc = newDocument();
Element rootNode = doc.createElement("data");
doc.appendChild(rootNode);
rootNode.appendChild(createDivisionsNode(doc));
rootNode.appendChild(createUsersNode(doc));
return doc;
}
private Element createDivisionsNode(Document doc) { ┓
Element divisionsNode = doc.createElement("divisions"); |
for (Division div : divs) { |
Element node = doc.createElement("division"); |
node.setAttribute("index", String.valueOf(rowIndex++)); |
... |
} |
return divisionsNode; |
} ┛④
private Element createUsersNode(Document doc) { ┓
Element usersNode = doc.createElement("users"); |
for (User user : users) { |
Element node = doc.createElement("user"); |
node.setAttribute("index", String.valueOf(rowIndex++)); |
... |
} |
return usersNode; |
} ┛⑤
private Element createElement(Document doc, String nodeName,String textContent) {
...
}
}
...
}

最終的にすべての変数のスコープとメソッドが
考察1:XmlBuilderクラスをインナークラスとして実装しているのはなぜ?
クラス内にクラスを宣言するインナークラスは使い出すとかなり便利です。今回のように特定の場所だけで使用される処理のインナークラスによる実装には、
実際に使用される個所のすぐ近くにクラスがあるのでわかりやすい
アクセスレベルをprivateにすることで、
元のクラスとの依存関係をstaticで制御できる
staticなインナークラスにすると元のクラスのフィールド変数にはアクセスできませんが、
新しいファイルを増やさなくてよい
初心者のころは新しいクラスを作成するのは勇気のいることです。特に新しいファイルを増やすとなんだかリーダーに怒られるんじゃないか?
まとめると、
考察2:divs、usersをコンストラクタで渡しているのはなぜ?
リスト6③のXmlBuilderのコンストラクタは組織とユーザ情報のリストが引数になっています。これは、
考察3:フィールド変数になりそうなもの
クラスを抽出した際にフィールド変数として保持したほうがよいものとしては、
考察4:これからどうする?
ここからの発展系としては、
今回のまとめ
今回は処理の分割について考えていきました。メソッド分割やクラス分割に答えはありませんが、
今まで、