If I have a simple class such as…
class Rectangle
{
private:
double length;
double width;
public:
void setLength(double l) { length = l; }
void setWidth(double w) { width = l; }
void getLength() { return length; }
void getWidth() { return width; }
void getArea() { return length * width; }
};
…and the person using it calls the mutator setWidth() with an invalid argument, say -1.0, what is the correct way to handle this? When I say correct, should I for example, change the return type from void to bool or possibly an int and return a value to indicate whether or not the operation occurred successfully, or am I to allow the value to be set since theoretically it will not break anything, but any values returned as a result, say from getArea() will be garbage and the user will have to debug what he/she did wrong?
Sorry if this is a silly question, but two text books later, and I’m still not quite sure about how classes I write should be implemented for others to use.
You have a couple choices. In the real world, it will depend on who is using your class (other internal code or public API) as well as conventions agreed upon by your company.
You can:
Throw Exception
Pros:
Cons:
Assert
Pros:
Cons:
Boolean Returns
Pros:
Cons:
Evaluate Data Type
Don’t be afraid to go back and check if the data type of your property makes sense for what you are doing. In this case, it does. However, I can think of times where developers have used standard integers when they really wanted unsigned integers or strings when they really needed a single character.