Like everyone I’m excited by this new proposal.  But…

> protocol Codable: Adopted by types to opt into archival. Conformance may be 
> automatically derived in cases where all properties are also Codable.

… can I make one suggestion.  Please do not repeat the mistakes of NSCoding in 
combining the encoding and decoding into a single protocol.  Just as there are 
Encoder and Decoder classes their should be Encodable and Decodable protocols 
(maybe have an aggregate Codable protocol for convenience but do not force it).

My reasoning:

Sometimes you only want to decode or encode and object and not vice versa.  
This is often the case with Web APIs and JSON serialisation.  

Eg:

Often an app only consumes (decodes) JSON encoded objects and never writes them 
out (a read only app for example). So the encode(to:) methods are completely 
redundant and someone adopting Codable should not be forced to write them.  

If only I had a dollar for all the times I’ve seen this sort of code in 
projects:

class MyClass : NSCoding {
init?(coder: NSCoder) {
  // ... some decoding code
}

func encode(with aCoder: NSCoder) {
   preconditionFailure(“Not implemented”)
}
}


Another example: 

Web APIs often take data in a different structure as input (i.e. “Request” 
objects) than they output.  These request objects are only ever encoded and 
never decoded by an application so implementing init(from:) is completely 
redundant.

Personally I think the approach taken by libraries like Wrap 
(https://github.com/johnsundell/wrap <https://github.com/johnsundell/wrap>) and 
Unbox (https://github.com/JohnSundell/Unbox 
<https://github.com/JohnSundell/Unbox>) is a much better design.  Encoding and 
decoding should not be the same protocol.

Yes I understand that Codable could provide no-op (or preconditionFailure) 
protocol extension based default implementations of init(from:) and encode(to:) 
(or try to magic up implementations based on the Codable nature of public 
properties as suggested in the proposal) but to me that seems like a hack that 
is papering over bad design.  I think this joint Codable design probably fails 
the Liskov substitution principle too.

So I again implore you to consider splitting Codable into two protocols, one 
for encoding and another for decoding.

Sorry if I’m repeating what other people have already said.  I’ve not read 
every response to this proposal on the list.

Regards





_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to