Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting the inputs to a constructor while keeping constructor code minimal

Well, I was told that I have to create a money class that accepts currency and value. The value should be stored as 2 integers, one representing the dollar value, then the other one in cents.

*It should accept the decimal value precise to two (2) decimal places. *

So I suppose I have to limit the cents value so that it should accept only 1 to 2 digit integers. Now, my problem is, my mentor told me that it is bad practice to do other stuff inside the constructor. How am I supposed to limit the input then if I'm not allowed to do anything with the constructor other than:

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.....
}

Any other ideas on how I am supposed to implement what was instructed of me? Why is it bad practice and is there a way to define constraints without being guilty of this bad practice???

like image 740
황현정 Avatar asked Jan 23 '26 10:01

황현정


1 Answers

What you are doing is validating the inputs to the constructor. Although in general "other stuff" in a constructor is not optimal, doing input verification code there is certainly warranted. Something like the following is a good pattern 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;
}

Btw, there is no point in calling super() at the front of your constructor unless. The Java language calls the base class constructor automagically under the covers.

like image 127
Gray Avatar answered Jan 26 '26 01:01

Gray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!