How to switch from CoreData to Realm in 5 minutes

Hi from the CodeBug :)
I have been at work disturbing programmers this week. Also, a new idea popped into this tiny head.
What if we could abstract ourselves from the database storage mechanism

Should your app really care about wether its storing its data in CoreData or a Text file?
The storage mechanism is not the core of your app. If you change it, users wont even notice. The storage mechanism is just a detail.

How do we design an iOS app such that you can easily change from CoreData to Realm?

protocol DatabaseProtocol {  
    func readDataFromDatabase() -> NSData
    func writeDataToDatabase(data: NSData)
    func dropDataBase()
    func createDatabase()
}

class DatabaseGate: NSObject {  
    static private let databaseSingleton = CoreDataImplementor()
    class func defaultDatabase() -> DatabaseProtocol {
        return databaseSingleton
    }
}

private class CoreDataImplementor: DatabaseProtocol {  
    func readDataFromDatabase() -> NSData {
        //write your implementation
        return NSData()
    }

    func writeDataToDatabase(data: NSData) {
        // write your implementation
    }
    func dropDataBase() {
        //write your implementation
    }
    func createDatabase() {
        //write your implementation
    }
}

Explanation:
1. We create a database singleton.
2. We make sure our defaultDatabase method does not return a specific object instead, it returns something which implements DatabaseProtocol
3. We implement that protocol with CoreData.

So how would you use this mechanism?

   let databaseGateway = DatabaseGate.defaultDatabase()
        databaseGateway.writeDataToDatabase(NSData())

Cool huh? No mention of CoreData, Realm or SQL. Just the plain simple truth: databaseGateway please write this NSData.

This will allow you to change from CoreData to Realm in 5 minutes.
Just implement the protocol with Realm and you're done. No autographs from the Code Bug today.

This speaks to a greater idea:
Program against an interface not an implementaiton

PS: Don't couple yourself to Realm or any other framework too much. You never know when you need to make yet another switch.

The Code Bug

A passionate iOS developer. Looking to radically improve the way we all develop software.

Amsterdam