1 /*
2  * Copyright (C) 2019 The Dagger Authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package dagger.example.atm;
18 
19 import java.math.BigDecimal;
20 import java.util.HashMap;
21 import java.util.Map;
22 import javax.inject.Inject;
23 import javax.inject.Singleton;
24 
25 /** A database that stores all of its data in memory. */
26 @Singleton
27 final class InMemoryDatabase implements Database {
28   private final Map<String, Account> accounts = new HashMap<>();
29 
30   @Inject
InMemoryDatabase()31   InMemoryDatabase() {}
32 
33   @Override
getAccount(String username)34   public Account getAccount(String username) {
35     return accounts.computeIfAbsent(username, InMemoryAccount::new);
36   }
37 
38   private static final class InMemoryAccount implements Account {
39     private final String username;
40     private BigDecimal balance = BigDecimal.ZERO;
41 
InMemoryAccount(String username)42     InMemoryAccount(String username) {
43       this.username = username;
44     }
45 
46     @Override
username()47     public String username() {
48       return username;
49     }
50 
51     @Override
deposit(BigDecimal amount)52     public void deposit(BigDecimal amount) {
53       checkNonNegative(amount, "deposit");
54       balance = balance.add(amount);
55     }
56 
57     @Override
withdraw(BigDecimal amount)58     public void withdraw(BigDecimal amount) {
59       checkNonNegative(amount, "withdraw");
60       balance = balance.subtract(amount);
61     }
62 
checkNonNegative(BigDecimal amount, String action)63     private void checkNonNegative(BigDecimal amount, String action) {
64       if (amount.signum() == -1) {
65         throw new IllegalArgumentException(
66             String.format("Cannot %s negative amounts: %s", action, amount));
67       }
68     }
69 
70     @Override
balance()71     public BigDecimal balance() {
72       return balance;
73     }
74   }
75 }
76