• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 dagger.example.atm.Database.Account;
20 import java.math.BigDecimal;
21 import javax.inject.Inject;
22 
23 /** Withdraws money from the ATM. */
24 final class WithdrawCommand extends BigDecimalCommand {
25   private final Outputter outputter;
26   private final Account account;
27   private final BigDecimal minimumBalance;
28   private final WithdrawalLimiter withdrawalLimiter;
29 
30   @Inject
WithdrawCommand( Outputter outputter, Account account, @MinimumBalance BigDecimal minimumBalance, WithdrawalLimiter withdrawalLimiter)31   WithdrawCommand(
32       Outputter outputter,
33       Account account,
34       @MinimumBalance BigDecimal minimumBalance,
35       WithdrawalLimiter withdrawalLimiter) {
36     super(outputter);
37     this.outputter = outputter;
38     this.account = account;
39     this.minimumBalance = minimumBalance;
40     this.withdrawalLimiter = withdrawalLimiter;
41   }
42 
43   @Override
handleAmount(BigDecimal amount)44   protected void handleAmount(BigDecimal amount) {
45     BigDecimal remainingWithdrawalLimit = withdrawalLimiter.remainingWithdrawalLimit();
46     if (amount.compareTo(remainingWithdrawalLimit) > 0) {
47       outputter.output(
48           String.format(
49               "you may not withdraw %s; you may withdraw %s more in this session",
50               amount, remainingWithdrawalLimit));
51       return;
52     }
53 
54     BigDecimal newBalance = account.balance().subtract(amount);
55     if (newBalance.compareTo(minimumBalance) < 0) {
56       outputter.output(
57           String.format(
58               "you don't have sufficient funds to withdraw %s. "
59                   + "your balance is %s and the minimum balance is %s",
60               amount, account.balance(), minimumBalance));
61     } else {
62       account.withdraw(amount);
63       withdrawalLimiter.recordWithdrawal(amount);
64       outputter.output("your new balance is: " + account.balance());
65     }
66   }
67 }
68