David M. Karr (64) [Avatar] Offline
#1
By the way, I noticed several examples in the book of code like this:

----------------
StringBuilder sb = new StringBuilder();

// movie table
sb.append("CREATE TABLE " + MovieTable.TABLE_NAME + " (");
sb.append(BaseColumns._ID + " INTEGER PRIMARY KEY, ");
sb.append(MovieColumns.HOMEPAGE + " TEXT, ");
sb.append(MovieColumns.NAME + " TEXT UNIQUE NOT NULL, "); // movie names aren't unique, but for simplification we constrain
sb.append(MovieColumns.RATING + " INTEGER, ");
sb.append(MovieColumns.TAGLINE + " TEXT, ");
sb.append(MovieColumns.THUMB_URL + " TEXT, ");
sb.append(MovieColumns.IMAGE_URL + " TEXT, ");
sb.append(MovieColumns.TRAILER + " TEXT, ");
sb.append(MovieColumns.URL + " TEXT, ");
sb.append(MovieColumns.YEAR + " INTEGER");
sb.append(");");
db.execSQL(sb.toString());
-------------

It is better to do this:
-------------------
String sql =
"CREATE TABLE " + MovieTable.TABLE_NAME + " (" +
BaseColumns._ID + " INTEGER PRIMARY KEY, " +
MovieColumns.HOMEPAGE + " TEXT, " +
MovieColumns.NAME + " TEXT UNIQUE NOT NULL, " + // movie names aren't unique, but for simplification we constrain
MovieColumns.RATING + " INTEGER, " +
MovieColumns.TAGLINE + " TEXT, " +
MovieColumns.THUMB_URL + " TEXT, " +
MovieColumns.IMAGE_URL + " TEXT, " +
MovieColumns.TRAILER + " TEXT, " +
MovieColumns.URL + " TEXT, " +
MovieColumns.YEAR + " INTEGER" +
");";
db.execSQL(sql);
-------------------

Besides the fact that it's more concise, it's a common misconception that "+" for strings always does string concatenation. In fact, inside a single expression it implicitly constructs a StringBuilder to produce the subexpression.

In addition, in this case all of those variable references are inlined, and when two inlined strings are concatenated together, the compiler produces a single constant. Adding all this together, the entire "sql" string is defined completely at compile time, resulting in no StringBuilder or string concatenation at all.

It's handy to use the Eclipse ByteCode Outline plugin to visualize this (http://andrei.gmxhome.de/bytecode/).