Skip to main content

Command Palette

Search for a command to run...

Good Ol' Switch Statements

Updated
2 min read
Good Ol' Switch Statements

Switch statements have been around since the early days of programming. In fact, the structure is identical across C-style languages.

switch (variable) {
    case 1:
        // Some code here
        break;
    case 2:
        // Some code here
        break;
    default:
        // Some code here
        break;
}

I’ve almost always used break statements between the cases. This is because I typically use a switch to replace multiple IF statements.

When building apps (like Android apps in the following example), there are some common use cases like:

  1. First time install of version 1 (create only; no update)

  2. Fresh install of version 2 or update version 1 to version 2

  3. Update from some older version to the current version (more than one version behind)

The way Android handled this back when I made my first app was clever to me. It was the first time I used a switch without breaks that I could recall. Please see a short example below:

@Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        switch(oldVersion)
        {
            case 1:
                db.execSQL(ADD_NEW_RECORDS);
            case 2:
                db.execSQL(CREATE_NEW_TABLE);
                db.execSQL(CREATE_ANOTHER_NEW_TABLE);
            case 3:
                db.execSQL(ALTER_TABLE);
                break;
            default:
                //log no update applied
        }
    }

The way this code works is like so:

We know it is an upgrade because Android is calling the onUpgrade method. If the old database version is “1” (which corresponds to the first release), this app is behind a couple of versions. The switch matches on “1” and executes the SQL in the constant variable to add some values to a table. Since the first case doesn’t have a break statement, it drops through and creates some new tables, and then finally alters the schema of another table.

If the app was already on version 4 of the database during an update (which happened when the update was a code-only update), the switch skips the database changes.

While I found this use case with a switch interesting, I imagine there are better ways to apply conditional transformations to a system, but this way is straightforward and easy to understand as long as there aren’t too many to manage.