Decodable and Encodable

The Decodable protocol is used to hydrate objects from some external representation. For example, it is used to parse JSON objects into structs or classes.

Decodable: A type that can decode itself from an external representation.

On the other hand, the Encodable protocol is used to store objects to some external representation. For example, it can be used to obtain a JSON representation of an object.

Encodable: A type that can encode itself to an external representation.

But why shouldn’t we use Decodable or Encodable in our domain model objects?

Let’s work with an example to answer that question. Assume we have the following JSON representation of a user:

{

"first_name":"dick",

"last_name":"richardson",

"mail":"drichardson@enclave.com",

"day_of_birth":7026198103

}

And we use a Decodable struct, named User , to both parse the JSON and represent a User in our domain model:

But what happens if the JSON changes? Let’s say that now the first and last name come within a name field:

{

"name":{

"first":"dick",

"last":"richardson"

},

"email":"drichardson@enclave.com",

"day_of_birth":7026198103

}

Due to this small change, the previous User struct now fails to parse the JSON data. We are forced to change the domain model to parse the new data model:

Good. Now the User struct parses the new JSON format but we have to change all the uses of firstName and lastName , replacing them for name.first and name.last respectively.

We have just changed our domain model due to a change in the data.