• 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 java.math.BigDecimal;
20 
21 /**
22  * Abstract {@link Command} that expects a single argument that can be converted to {@link
23  * BigDecimal}.
24  */
25 abstract class BigDecimalCommand extends SingleArgCommand {
26 
27   private final Outputter outputter;
28 
BigDecimalCommand(Outputter outputter)29   protected BigDecimalCommand(Outputter outputter) {
30     this.outputter = outputter;
31   }
32 
33   @Override
handleArg(String arg)34   protected final Result handleArg(String arg) {
35     BigDecimal amount = tryParse(arg);
36     if (amount == null) {
37       outputter.output(arg + " is not a valid number");
38     } else if (amount.signum() <= 0) {
39       outputter.output("amount must be positive");
40     } else {
41       handleAmount(amount);
42     }
43     return Result.handled();
44   }
45 
tryParse(String arg)46   private static BigDecimal tryParse(String arg) {
47     try {
48       return new BigDecimal(arg);
49     } catch (NumberFormatException e) {
50       return null;
51     }
52   }
53 
54   /** Handles the given (positive) {@code amount} of money. */
handleAmount(BigDecimal amount)55   protected abstract void handleAmount(BigDecimal amount);
56 }
57