4 ms·
My favorite "easy win" find from learning Haskell last year was just the `newtype` keyword, which basically just let you alias primitive types with zero runtime
by hiAndrewQuinn 4y ago
My favorite "easy win" find from learning Haskell last year was just the `newtype` keyword, which basically just let you alias primitive types with zero runtime impact.
`newtype Email = Email String` and `newtype Username = Username String` are just `String`s with guard rails.
- nerdponx 4y agoPython's type annotation system has this feature too: from typing import NewType UserId = NewType('UserId', str) user_id: UserId user_id = "abc" # Type check error user_id = UserId("abc") # OK # At runtime, a NewType is the identity function s1: str = "abc" s2: UserId = UserId(s1) assert s1 is s2 Docs: https://docs.python.org/3/library/typing.html#newtype https://docs.python.org/3/library/typing.html#newtype Runtime: https://tio.run/##TU49D4JADN37K544CIkLupk4OBoTXXQ2CKdcDHeXtsTw6/GQoHZp@9r3ETqtvVv3/Z19A@2CdQ/YJnhWHM3r3AVDdBHD@wrbCUkXI7JYQpQzojauV1ttMOJfIFKS4lYm@NYcgwDK2pRPGGbPf78jO/1QsuH3dCCaY6fg1qltzBLFlAFWoHVslYkn7XBvXanWO5J8M8SavElWU66fheQZFRJnheSDlKyIAlunaXI6zJKs798 https://tio.run/##TU49D4JADN37K544CIkLupk4OBoTXXQ2CKdcDHeXts... Type checking: https://mypy-play.net/?mypy=latest&python=3.10&flags=show-error-codes%2Cstrict&gist=2f9be920806f100b1654770dca7d3639 https://mypy-play.net/?mypy=latest&python=3.10&flags=show-er...
- yakshaving_jgt 4y agoYou probably want smart constructors, as you probably don't want the possibility for a 10,000 character username to float through your system.