I have a class with some members whose value has a finite range. For example
class Sphere
{
public:
void setRadius(double radius)
{
m_radius = radius;
}
private:
double m_radius; // must >= 0.
};
I also have a dialog to input the radius. I can check the radius validation in the setRadius() method, or check in the dialog. Which way is better? This seems quite a common problem. What is the conventional way or best way? Thanks.
In OOP, you typically have the validation occur in the function and have the function throw an exception if the value is not within your accepted range, in your case.
However, if you’re doing this for a class and aren’t expected to know about throwing/catching exceptions yet, you can do one of two things:
Something like this:
Notice that you don’t initiate/change the value stored in m_radius if the argument of “radius” is not within your range. There would be no point in changing the value of m_radius to an unacceptable value — it’s a waste of time.
If you want to know more about exceptions, you can refer to this page for a greater understanding of what an exception is: http://www.cplusplus.com/doc/tutorial/exceptions/
So, i++ and to conclude, the convention is to check it in the method and have the method throw an exception if the value is out of the accepted range. You may not have to if you’re in a class and haven’t covered exceptions yet though. Best of luck to you! 🙂