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???
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:
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.