(no title)
Archelaos | 20 days ago
When the type is more complex, specific contraints should be used. For a real live example: I designed a type for the occupation of a hotel booking application. The number of occupants of a room must be positiv and a child must be accompanied by at least one adult. My type Occupants has a constructor Occupants(int adults, int children) that varifies that condition on construction (and also some maximum values).
lelanthran|20 days ago
Or, you could do what I did when faced with a similar problem - I put in a PostgreSQL constraint.
Now, no matter which application, now or in the future, attempts to store this invalid combination, it will fail to store it.
Doing it in code is just asking for future errors when some other application inserts records into the same DB.
Business constraints should go into the database.
imtringued|20 days ago
Archelaos|20 days ago
Note that this does not violate the "Parse, Don't Validate" rule. This rule does not prevent you from doing stupid things with a "parsed" type.
In other cases, I use its cousin unchecked on int values, when an overflow is okay, such as in calculating an int hash code.