Step3:処理単位で分割する
次に、
- 処理1:XML用の組織、
ユーザデータを取得 - 処理2:XMLの作成
- 処理3:XMLの出力
このうち処理2、
...
public ActionResult index() throws Exception {
List<Division> divs = userService.getDivisions();
List<User> users = userService.getUsers();
Document doc = buildDocument(divs, users);
writeDocument(doc);
}
private Document buildDocument(List<Division> divs, List<User> users)
throws ParserConfigurationException {
int rowIndex = 1; ―①
Document doc = newDocument();
Element rootNode = doc.createElement("data");
doc.appendChild(rootNode);
Element divisionsNode = doc.createElement("divisions");
for (Division div: divs) {
Element node = doc.createElement("division");
node.setAttribute("index", String.valueOf(rowIndex++)); ―②
...
}
rootNode.appendChild(divisionsNode);
Element usersNode = doc.createElement("users");
for (User user: users) {
Element node = doc.createElement("division");
node.setAttribute("index", String.valueOf(rowIndex++)); ―③
...
}
rootNode.appendChild(usersNode);
...
}
private void writeDocument(Document doc) {
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
DOMSource source = new DOMSource(doc);
...
}
...

考察:制御と処理の分割のよくある例
制御と処理を分ける場合によくあるパターンを紹介します。
ループと、ループの中の処理
ループの中では、
for (Item item : items) {
if (item.isNotEmpty()) {
...
...(長いコード)
...
}
}
for (Item item : items) {
process(item)
}
private void process(Item item) {
if (!item.isNotEmpty()) { return; }
...
...(長いコード)
...
}
// ループ以外からも利用可能!
process(getLastItem());
if文とその中の処理
if文の中の長い処理を別メソッドに分割することで、
if (cart.isEmpty()) {
// カートが空ならエラー
loggingError(cart);
} else {
// それ以外なら精算
checkout(cart);
}
try~catch~finallyとその中の処理
例外処理では
次のコードはJUnit 4.
setUp();
try {
runTest();
} catch (Throwable running) {
exception= running;
} finally {
try {
tearDown();
} catch (Throwable tearingDown) {
if (exception == null) exception= tearingDown;
}
}
制御構造のtry~catch~finally と、