encapsulation & constructors
I have a little experience but just getting started with formal training. I couldn't find information on my question elsewhere in this forum so here it is. Hopefully it's clear.
We've been learning encapsulation and constructors this week. I had an assignment that required creating a default constructor for a Rectangle class and to overload this constructor with another that would accept a height and width. That was no problem.
It was also required that we provided get and set methods for both height and width. Again, this was no problem.
My question comes from the requirement that the custom constructor would validate the height and width provided such that they were both > 1 and < 30. Again in and of itself, no problem. But this got me wondering about the set methods. How would I do the same validation for the set method?
The assignment didn't ask for it, but if it was a real world thing, my thought is that the height and width would have to be > 1 and < 30 at all times. Not just on instantiating a new Rectangle. By the assignment, I could meet the criteria for instantiation but then later use the set method to increase the dimensions out of the limits.
So my next thought was why not do the validation within the set methods rather than in the constructor. The constructor could then invoke the set method and pass the appropriate arguments that were provided. In this manner, my validation code would only be in the set method and not both the set method and constructor.
Is there a problem with this direction?