0

I have been searching for an answer for this question but seems like there is mixed opinions hence its a design matter.

Anyway, I am creating a simple Money Class that has two private instance variables.

private int dollars, cents;

Now, since it doesn't make sense to have lets say 0 dollars and 500 cents because then you would have 5 dollars and 0 cents, is it a good idea to make sure that dollars and cents are represented properly in the constructor and change them if they werent?

I was thinking to validate input in my setters methods and call them from the constructor but after reading this calling setters from a constructor I doubt that its the best thing to do.

Community
  • 1
  • 1
Zafer Khourdaji
  • 81
  • 1
  • 1
  • 7
  • 2
    you can have a private method that is called by both the setter and the constructor so you don't have to duplicate the logic. – Danny Dec 04 '16 at 02:02
  • 2
    A better way is to eliminate the need to do this; I'd just represent the money entirely in terms of cents, and just display it in dollars as needed. – JesseTG Dec 04 '16 at 02:09
  • 1
    You may want to consider making your `Money` class immutable. All methods which mutate the amount of money (after the constructor is finished) should return a new instance. The benefit of doing this is that it will make modifying the dollar amount a much safer action. You won't have to worry about methods silently monkeying with the dollar amount when you don't want them to. – 4castle Dec 04 '16 at 02:25

0 Answers0