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:
First time install of version 1 (create only; no update)
Fresh install of version 2 or update version 1 to version 2
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.
Subscribe to my newsletter
Read articles from Doug Dawson directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Doug Dawson
Doug Dawson
I've been doing computer-related things since I was a kid on my dad's Franklin ACE 1000 and his Tandy. I've built PCs, repaired servers, wired networks by hand, administered servers and built numerous applications. I've coded in Perl, PHP, Java, VB, C#, VB.NET, JS and probably a few others. I'm a jack-of-trades technologist. I transitioned into leadership several years ago from a senior .NET developer. I'm currently a Delivery Manager and I lead an agile software development team.