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:

  1. the die constructor protected , accepts std::vector<double>. have static public method performs data validation, , returns pointer new die object if successful, , null otherwise.

  2. create probabilityvector class, wraps around std::vector<double>, , implement data validation there (with protected constructor + public static method above). die constructor accepts (pointer a) probabilityvector.

  3. implement separate probabilityvectorvalidation class, static method on std::vector<double> returning bool. then, when necessary, use method before passing std::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

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

inno setup - TLabel or TNewStaticText - change .Font.Style on Focus like Cursor changes with .Cursor -