限制构造函数的输入,同时保持构造函数代码最少

황현정*_*황현정 3 java constructor

好吧,我被告知我必须创建一个接受货币和价值的货币类。该值应存储为 2 个整数,一个代表美元价值,另一个代表美分。

*它应该接受精确到两 (2) 位小数的十进制值。*

所以我想我必须限制美分值,以便它只接受 1 到 2 位整数。现在,我的问题是,我的导师告诉我,在构造函数中做其他事情是不好的做法。如果不允许我对构造函数执行任何操作,除了:

public class Money {
    Currency currency;
    int dollar;
    int cents;

    public Money(Currency currency, int dollar, int cents) {
        super();
        this.currency = currency;
        this.dollar = dollar;
        this.cents = cents;
    }
    ..... other code.....
}
Run Code Online (Sandbox Code Playgroud)

关于我应该如何实施对我的指示还有其他想法吗?为什么这是不好的做法,有没有办法定义约束而不犯这种不好的做法???

Gra*_*ray 5

您正在做的是验证构造函数的输入。虽然一般来说构造函数中的“其他东西”不是最优的,但在那里输入验证码肯定是有保证的。像下面这样的东西是一个很好的模式 IMO:

public Money(Currency currency, int dollar, int cents) {
    this.currency = currency;
    this.dollar = dollar;
    // validate that cents is 0 to 99
    if (cents < 0 || cents > 99) {
        throw new IllegalArgumentException("Invalid cents value: " + cents);
    }
    this.cents = cents;
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,super()除非在构造函数的前面调用,否则毫无意义。Java 语言在幕后自动调用基类构造函数。