Hacker News new | ask | show | jobs
by Zababa 1845 days ago
They can, this is a misconception. Create a new type, and make it so that it's only produced by a function that checks if the age is superior to 18.
1 comments

That's a poor hack, it moves an invariant that could be enforced at compile time to not much more than a convention that has to be preserved by code review.

E.g. a colleague implements de-serialisation for your type but adds an empty constructor to make their life easier. You might not learn there's a hole in the boat before your first bug.

I wouldn't call it a poor hack. In a way it's a parser, which aren't really poor hacks, but can be abused. Sure, it's not perfect and I'd like it better if it was checked at compile time, but it's way better than using a simple int. Also, the moment you have a bug, tracking it is really easy: just list the functions that returns this specific type.