davidevincenzi / DataLayer

1 stars 0 forks source link

Thread safety in Structs #4

Open davidevincenzi opened 6 years ago

davidevincenzi commented 6 years ago

Just wanted to note that thread safety imo is really something we need to live without. Even in the Struct solution, we need to be careful when updating the entities, as this can lead to crashes, as you can see in the latest commit in the _data_layer_withstructs branch: https://github.com/davidevincenzi/DataLayer/commit/7d57bc08fdb3f18f2cfc98d2827d3fcaab1ece67

Basically with Structs we're safe when reading properties, but not when writing them. With Protocols, this is never safe. I tried to workaround it with this commit https://github.com/davidevincenzi/DataLayer/commit/550a720de639e3b949cc92efbcdb9f165f494dce and it works, you can read and write in background threads. But it requires lots of boilerplate code, so I don't know if it's worth the effort.

nfgrilo commented 6 years ago

If we opt for a Higher Level Persistence API like the one on protocol_decouple branch, we could do something like this, so it fails earlier, on development:

https://github.com/davidevincenzi/DataLayer/blob/protocol_decoupled/DataLayer/Persistence/Persistence%20(Storable%20object%20%26%20context)/NSManagedObjectContext%2BStorageContext.swift#L81-L83

Basically, the idea is to compare the object associated context with the context being used for the operation. We could either fail immediately or, eventually, go a little further and do something more under the hood:

This way the user could still succeed in its operation, and we would know something to fix from Sentry.

Disclaimer: not tested