[swift-evolution] Proposal: Introduce User-defined "Dynamic Member Lookup" Types
matt+swift-evolution at diephouse.com
Thu Nov 30 05:46:35 CST 2017
I think this is a bad idea.
I’ve worked with APIs like this in Perl, Ruby, and Obj-C. Even in a dynamic language, IMO it’s almost always a mistake to use them. It makes code harder to reason about when reading and debugging.
This seems especially true with Swift because you can no longer autocomplete or introspect these sort of things. (Not that Swift has that much introspection at the moment. Aside: how would these work, if at all, with `KeyPath`s?)
I personally don’t want to work with APIs like this. And while I can understand the appeal of easier interop—especially if you’ve come into a large library of Python code—IMO this would inevitably lead to other misuses of dynamic lookups in 1st- or popular 3rd-party libraries.
But apart from my general philosophical complaints, I have 2 specific criticisms of the proposal:
1. I don’t think this would actually be good for writing Python
The examples in the proposal are very shallow, highlighting single lookups. But what are the types of the returned values?
Since all the lookups resolve to a single type, it must either (1) require casting or (2) only use dynamic lookups.
If you’re casting, then the dynamic lookups serve no real purpose. Any serious development project would quickly add a typed interface on top of the dynamic one. It would be better to build this typing into the bridging instead of performing dynamic lookups.
If you’re only using dynamic lookups, then you’re no longer really writing Swift. Any real typing has gone out the window and you’re left writing a strange variant of Python. When you do need to get a value out, I’d imagine you’d need to cast.
I think the proposal should include a more complete example that demonstrates how meaningful interop code could be written.
Swift already has `Codable`, which provides more automatic and more type-safe (in that it encourages all-or-nothing decoding) JSON decoding. On that basis alone, I don’t think it’d be useful.
But this also ignores the ugly reality of JSON: the difficulty isn’t in accessing fields. The real trouble comes when you try to map a real, evolved, flawed API into a well-typed, thought-out data model. (This criticism applies to `Coding` too. Mapping JSON to an `enum` gets ugly quick.)
Arguably, this proposal’s JSON interface would be better for throwaway scripting, but IMO that case isn’t worth optimizing for.
> On Nov 27, 2017, at 1:04 AM, Chris Lattner via swift-evolution <swift-evolution at swift.org> wrote:
> I’d like to formally propose the inclusion of user-defined dynamic member lookup types.
> Here is my latest draft of the proposal:
> An implementation of this design is available here:
> The implementation is straight-forward and (IMO) non-invasive in the compiler.
> swift-evolution mailing list
> swift-evolution at swift.org
More information about the swift-evolution