📝 Parse, don’t validate is another one good blog post about writing better type annotations. I short, instead of checking the correctness of values everywhere (or even worse, implicitly assuming they are valid), check them once, convert it into a new type, and then accept that type in every place where an already validated value is expected. For example, in Python:


Username = NewType('Username', str)

def parse_username(raw: str) -> Username:
    ...```



And then all other functions that expect a valid type should be annotated with `Username`.

There is more in this blog post, with examples, corner-cases, and all that stuff, so I recommend to read it. The code examples are on Haskell, but they should be easy to understand (if you're not easily scared by monads) and the techniques can be translated to the language of your choice.