http://bufferings.hatenablog.com/entry/2015/05/06/000943 で紹介されていた「手続き型で典型的」かつ、かなりアレなコードを自分なりにリファクタリングしてみました。
public Result execute(Input in) { | |
try { | |
if ( !IsSelectedInRange(in.getSelected(), 1, 10) || | |
!IsCoinCountInRange(in.getCoins(), 1, 100) ) { | |
throw new IllegalArgumentException(); | |
} | |
List<Integer> smallCoins = new ArrayList<>(); | |
int sumOfLargeCoins = 0; | |
for (Integer coin : in.getCoins()) { | |
if (coin == 1 || coin == 5) { | |
smallCoins.add(coin); | |
} else | |
if (coin == 10 || coin == 50 || coin == 100 || coin == 500 ) { | |
sumOfLargeCoins += coin; | |
} else { | |
// throw new IllegalArgumentException(); | |
} | |
} | |
Product product = dao.findById(in.getSelected()); | |
if (product == null) { | |
return createResultWitoutProduct(in.getCoins()); | |
} | |
if (product.getPrice() < sumOfLargeCoins) { | |
Result result = new Result(); | |
result.setProduct(product); | |
sumOfLargeCoins -= product.getPrice(); | |
List<Integer> coins3 = new ArrayList<>(); | |
coins3.add(500); | |
coins3.add(100); | |
coins3.add(50); | |
coins3.add(10); | |
for (Integer coin : coins3) { | |
while (sumOfLargeCoins > coin) { | |
smallCoins.add(coin); | |
sumOfLargeCoins -= coin; | |
} | |
} | |
result.setCoins(smallCoins); | |
return result; | |
} | |
return createResultWitoutProduct(in.getCoins()); | |
} catch (Exception e) { | |
LOG.error(e); | |
return createResultWitoutProduct(in.getCoins()); | |
} | |
} | |
boolean IsSelectedInRange(Integer selected, int from, int to) | |
{ | |
return selected != null && from <= selected && selected <= to; | |
} | |
boolean IsCoinCountInRange(List<Integer> coins, int from, int to) | |
{ | |
return coins != null && from <= coins.size() && coins.size() <= to; | |
} | |
Result createResultWitoutProduct(List<Integer> coins) | |
{ | |
result = new Result(); | |
result.setCoins(coins); | |
result.setProduct(null); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
osamutake commentedMay 13, 2015
編集履歴についてのコメントは http://dora.bk.tsukuba.ac.jp/~takeuchi/?プログラミング%2F作法%2FHello.java にあります。
Mitsuyuki.Shiiba さんのオリジナルのコードが Gist 上に https://gist.github.com/bufferings/9414995751687177e882 としてあるのですが、特定のリビジョンから Fork する方法が解らず、コピペで新しい Gist を作ることになってしまいました。たぶん間違った方法なんだと思うのですが、どうもすみません。
ここからも解るように、私は Gist も、実は Java もあまりよく分かっていません。普段は Ruby とか JavaScript とか C# とか良く書いてます。Java のコンパイル環境もないので、タイプミスについてもご容赦下さい。