c++ - Data Validation in a Constructor? -
i beginner oo-programming, , question handling data validation in particular design. have read this thread similar problem, , second solution, recommends re-designing constructor interface such invalid values impossible, wonder whether idea applicable case. have outlined thoughts below , know if people agree ideas.
i have die
class, constructed passing vector of probabilities. probabilities must non-negative, , must add 1.0.
class die { public: die(/* probability vector. */); int roll(); }
i can think of several options implement data validation:
the
die
constructor protected , acceptsstd::vector<double>
. have static public method performs data validation, , returns pointer newdie
object if successful, ,null
otherwise.create
probabilityvector
class, wraps aroundstd::vector<double>
, , implement data validation there (with protected constructor + public static method above).die
constructor accepts (pointer a)probabilityvector
.implement separate
probabilityvectorvalidation
class, static method onstd::vector<double>
returningbool
. then, when necessary, use method before passingstd::vector<double>
die
constructor.
the disadvantage of (1) validation carried out every time die
created, though may not necessary. (2) gets around problem, i'm not sure if protected constructor + static public approach elegant, because involves raw pointers. (3) looking attractive option, seems less robust (1) , (2)?
Comments
Post a Comment