ソースを参照

refactored computeResult to be cleaner

Lauren Green 7 年 前
コミット
8635f94f23
共有1 個のファイルを変更した23 個の追加8 個の削除を含む
  1. 23
    8
      src/main/java/io/zipcoder/tc_spring_poll_application/controller/ComputeResultController.java

+ 23
- 8
src/main/java/io/zipcoder/tc_spring_poll_application/controller/ComputeResultController.java ファイルの表示

@@ -29,14 +29,19 @@ public class ComputeResultController {
29 29
     @RequestMapping(value = "/computeresult", method = RequestMethod.GET)
30 30
     public ResponseEntity<?> computeResult(@RequestParam Long pollId) {
31 31
         VoteResult voteResult = new VoteResult();
32
-        Iterable<Vote> allVotes = voteRepository.findById(pollId);
33
-        Map<Long, Integer> mapOptions = new HashMap<>();
34
-        Collection<OptionCount> optionCounts = new ArrayList<>();
35
-        int totalVotes = 0;
32
+        Map<Long, Integer> mapOptions = mapVotes(voteRepository.findById(pollId));
33
+        Collection<OptionCount> optionCounts = collectOptionCounts(mapOptions);
34
+
35
+        voteResult.setResults(optionCounts);
36
+        voteResult.setTotalVotes(getTotalVote(optionCounts));
36 37
 
38
+        return new ResponseEntity<>(voteResult, HttpStatus.OK);
39
+    }
40
+
41
+    private Map<Long, Integer> mapVotes(Iterable<Vote> allVotes) {
42
+        Map<Long, Integer> mapOptions = new HashMap<>();
37 43
         for(Vote vote: allVotes) {
38 44
             Long id = vote.getOption().getId();
39
-            totalVotes++;
40 45
             if(!mapOptions.containsKey(id)) {
41 46
                 mapOptions.put(id, 1);
42 47
             } else {
@@ -45,15 +50,25 @@ public class ComputeResultController {
45 50
                 mapOptions.put(id, count);
46 51
             }
47 52
         }
53
+        return mapOptions;
54
+    }
55
+
56
+    private Collection<OptionCount> collectOptionCounts (Map<Long, Integer> mapOptions) {
57
+        Collection<OptionCount> optionCounts = new ArrayList<>();
48 58
 
49 59
         for(Long i: mapOptions.keySet()) {
50 60
             OptionCount optionCount = new OptionCount(i, mapOptions.get(i));
51 61
             optionCounts.add(optionCount);
52 62
         }
63
+        return optionCounts;
64
+    }
53 65
 
54
-        voteResult.setResults(optionCounts);
55
-        voteResult.setTotalVotes(totalVotes);
66
+    private int getTotalVote(Collection<OptionCount> optionCounts) {
67
+        int totalVotes = 0;
56 68
 
57
-        return new ResponseEntity<>(voteResult, HttpStatus.OK);
69
+        for(OptionCount o: optionCounts) {
70
+            totalVotes += o.getCount();
71
+        }
72
+        return totalVotes;
58 73
     }
59 74
 }