Last active
August 29, 2015 14:21
http://bufferings.hatenablog.com/entry/2015/05/06/000943 で紹介されていた「手続き型で典型的」かつ、かなりアレなコードを自分なりにリファクタリングしてみました。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 || product.getPrice() >= sumOfLargeCoins ) { | |
return createResultWitoutProduct(in.getCoins()); | |
} | |
Result result = new Result(); | |
result.setProduct(product); | |
int remainder = sumOfLargeCoins - product.getPrice(); | |
List<Integer> largeCoinList = getLargeCoinList(); | |
for (Integer coin : largeCoinList) { | |
while (remainder > coin) { | |
smallCoins.add(coin); | |
remainder -= coin; | |
} | |
} | |
result.setCoins(smallCoins); | |
return result; | |
} 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; | |
} | |
List<Integer> getLargeCoinList() | |
{ | |
List<Integer> list = new ArrayList<>(); | |
list.add(500); | |
list.add(100); | |
list.add(50); | |
list.add(10); | |
return list; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
編集履歴についてのコメントは 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 のコンパイル環境もないので、タイプミスについてもご容赦下さい。