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 had to have break statements between the cases. This is because I usually use a switch to replace multiple IF statements.
When I created one of my first Android apps, there are some common use cases like:
First time installed of version 1
Update from version 1 to version 2
Delayed update from version 1 to version 3+
The way Android handled this back then was clever to me and was the first time I used a switch without breaks. 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 version. 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, it drops through and creates some new tables, and then finally alters the schema of another table.
If the app was already on version 3 of the database, the switch skips the database changes that the this version of the app presumably already has and just runs the alter table SQL.
While I found this use cases 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.
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.