3 ms·
Oh yeah, checking types the way the author was doing it is explicitly an antipattern. If you want to do duck typing, you should check that the object acts like
by StavrosK 5y ago
Oh yeah, checking types the way the author was doing it is explicitly an antipattern. If you want to do duck typing, you should check that the object acts like you expect (e.g. that it has a defined "addition" operation, if you want to add it to something), rather than that it's of a specific type.
If you want to do that, you should use the static type system.
- void_mint 5y agoGotcha - that makes sense and is what I would've expected. Thanks for the info!
- rbanffy 5y agoYou may want to explicitly test for a type depending on the interface contract. If you build software for consumption by others, you may want to ensure that, whatever the inputs, it’ll always return something you said would be returned. While the consumer would be insane not to verify what you sent, it’s polite not to send a complex number when someone is expecting a count.
- StavrosK 5y agoCertainly, but you're typically much more in control of what you send than what you receive.
- rbanffy 5y agoYou may also want to do sanity checks but, in those cases, I tend to deliberately abuse the inputs. Send a string, a byte string, some invalid UTF-8, an emoji, an invoice, and ensure that the thing can take more abuse than what the manual says. If, however, the manual says “integer” then it should complain loudly the user is breaking the contract.
- StavrosK 5y ago> If, however, the manual says “integer” then it should complain loudly the user is breaking the contract. Yep, that's why I prefer mypy/typeguard and type annotations for those sorts of things over checking in the body. It's frequently much, much easier to read, and self-documenting, since most IDEs have support for that when calling the function nowadays.
- utucuro 5y agoThe post is not about what you're sending, it is about making sure what you're receiving is what you're getting. The motivation begins with: "Many of our programs accept input from the user. Often we need to validate this input before continuing processing and, in the case of errors, inform the user of any problems."
- StavrosK 5y agoThe post I was replying to is about what you send, though.