4 ms·
In theory, yeah... in practice, as someone who uses Go and Python with mypy (which supports structural type-checking using the Protocol interface) professionall
by mjr00 7y ago
In theory, yeah... in practice, as someone who uses Go and Python with mypy (which supports structural type-checking using the Protocol interface) professionally, I haven't seen it happen. It's easy to think of contrived examples like the one in the post, where Cat/Dog/Table all implement GetLegCount(), but in practice your interface methods usually aren't that simple, and interface signatures like
func InsertFoo(*sqlx.DB, Foo) (int64, error)
are very unlikely to be unintentionally implemented.
- mrkeen 7y agoI tend to use nominal types a lot in other languages, so I have a lot of types with id() or value(). Would those be mixed up?
- masklinn 7y agoIf the interfaces have only id/value with matching parameters and return types then yes the interfaces would be functionally identical and all objects satisfying one of the interfaces would satisfy the others.
- morelisp 7y agoThey would be, but it's also unlikely you would be able to write something useful using only the id and value such that you might confuse something. There's some "self-limiting" - the smaller the interface, the more likely you get accidental implementation, but also the less likely you are to confuse them in a way that typechecks but actually does something unexpected. A practical example might be io.Closer - I am certain I implemented this in a dozen types I never intend to pass to any io functions. But no io functions actually take just a Closer, and if I did write some generic cleanup routine that only requires a Closer, it's probably fine and maybe even good if it works on byte IO and gRPC connections and Kafka streams. (Especially without generics, it might be the best I can do.)
- deleted 7y ago[deleted]
- zaphar 7y agoIn practice if your 'id() string' method returns an id as a string for the object doesn't it do what you need it to? So you actually need to care whether the intended to satisfy your contract or not? You might care if you expect the Id string to look a particular way. But then you probably wanted to use a type other than string for the return type.
- mrkeen 7y ago> you probably wanted to use a type other than string for the return type. That's the point. In order for (String userId) to not be confused with (String password), I wrap them with nominal types UserId and Password. If the language looks at both UserId and Password and decides they're interchangeable because they both satisfy the contract 'contain a String', then that completely negates the point.
- Nullabillity 7y agoAnd at that point, you have.. nominal types with less documentation?