Quick-and-dirty flat-file storage

Not every app needs cloud storage with a SQLite cache.

I’m going to let you in on a little secret that helps me prototype apps quickly.  Sometimes, when nobody’s looking, I just write my data to disk. I don’t build a cloud backend.  I don’t build a SQLite database. I just serialize my data to JSON and write it to files on the disk.  It’s really easy.

There are definitely some drawbacks to this approach, so if your head is about to light on fire with anger towards me, skip to the Caveats section below.

The code

Here’s what it takes; it’s just a couple of lines of Kotlin.  Say I’ve got a FooConfiguration object that I want to persist to disk.  It’s complicated enough that I don’t want to put it in SharedPreferences, so we’re going to write it to a file.

Step 1: We have a couple of dependencies to bring in.

Step 2: we serialize the object to JSON and write it to disk.

Step 3: When we need to read that data, we read from disk and deserialize from JSON.

That’s it.  Persistent storage, done.

Caveats

Like I mentioned at the beginning, this is something I do to get an app idea off the ground quickly.  When you go to scale this up, you’re going to run into drawbacks.

  • Sync & conflicts – If you try to sync this storage over a cloud file store (e.g. Dropbox, Google Drive, etc), or build some import/export functionality, you’re quickly going to run into this question — How do I handle conflicts? This is a hard problem, and the best advice is to build your storage model such that somebody else handles that complexity.
  • Data model evolution – If you change your data model, you need to ensure that it’s backwards-compatible, or else you’ll lose data from previously-stored objects.
  • Security – storing your data to local disk may not make sense, depending on the sensitivity of the data.  This is highly dependent on your specific needs, but keep it in mind.
  • Local-only – The only copy of the user’s data is on their device.  If you want to build any kind of social app where users interact with each other’s data, this isn’t going to get the job done.

My point here is, this isn’t a perfect solution, and it may be downright bad for your app.  Don’t take my advice blindly.

Ship It

I have multiple apps in the Play Store using this method right now.  No, I’m not going to tell you which ones. My point is, if you’re working on an app but you’re getting stuck on building a backend, this is a way to punt on the complexity of your persistent storage.  Build it quick-and-dirty for now, so you can focus on the app; revisit a more scalable solution for storage when you’re ready.

 

Author: jeb

Views expressed here are my own and do not necessarily reflect the views of my employer.