I’ve written a database manager to handle the queries in my Android application and the function that I use to delete a row does some weird stuff. Here’s the function:
public synchronized boolean removeChannel(String channel_name) {
IMrekMessageDbAdapter messageAdapter = new IMrekMessageDbAdapter(this.context);
messageAdapter.open();
long id = getChannelId(channel_name);
if (!messageAdapter.clearChannel(id)) {
// return false if we can't clear the messages for the channel
// this likely means that the channel doesn't actually exist and something
// is messed up.
return false;
}
boolean ret = database.delete(DATABASE_TABLE, KEY_ID + " = ?", new String[]{((Long)id).toString()}) > 0;
return ret;
}
Now, with the code like this, it hits the if which evaluates to false and therefore skips it. However it skips the assignment of ret and goes right to the return statement (and therefore also skips the database.delete() call. The debugger also doesn’t show ret in the scope.
Another question pointed out that sometimes it might skip lines because of the way the Android compiler optimizes the bytecode, since that is what it’s really tracing through and not the java. However, if I comment out the return false; inside the if it doesn’t skip the database.delete() call/assignment to ret. And it actually does delete the line it is supposed to.
My question is basically: Why would it skip the rest of the function because of a return statement inside an if block that is not getting executed?
As it turns out, it was because of the return statement inside of the
if. I learned that you are always only supposed to have one return statement inside a function. As demonstrated here, having others can cause problems. Despite not going into theifblock, it was executing the first return.