Decoupling Code

I’ve written before about my use of SQLite and the GRDB framework in my new app ExerPlan. After spending more time coding and getting to grips with the approach I detailed here, I’ve made the decision to alter the approach again.

While GRDB is an excellent framework, it’s not part of the Swift standard library and as such there may come a time when it’s no longer supported or actively developed. I decided I didn’t want my code so tied to the framework that replacing it could be an issue. The solution? To make a small alteration that would decouple me from GRDB, while still letting me use the power of GRDB as I was before.

I split my data code across two objects; one is a Struct that is basically a 1-to-1 mapping of a database table. However, it has no knowledge of how it will be persisted as I’ve removed all references to GRDB. The second type is a class that does reference GRDB, and is where all the persistence methods have been moved to.

The persistence class contains one “save” method per table, and takes a value of the Struct as a parameter.

struct Plan
{
   var planID: Int64?
   var planName: String

   func save()
   {
      Persist.save(self)
   }

}

class Persist
{
   func save(plan: Plan)
   {
       // Create a GRDB version of the Plan object
       // Then we can use GRDB to persist
   }

   func save(activity: Activity)
   {

   }
}

Having split the code like this, my persistence layer is now decoupled from the objects it is persisting. If I decide to stop using GRDB, I only need to re-write the save methods in the Persist class and the rest of the code will carry on working in the same way.

I have also created a Fetch class, which works in a similar way to Persist, but is for returning data that my app requires. Again, this means I only need replace code in Fetch if I were to use a new data access framework in place of GRDB.

It’s been a long journey getting to this point with Swift, GRBD, and iOS coding in general. I’m happy with where I’m at now and I’ll be moving on to the next stage, learning how to do UI programming with Swift and iOS.