Is the following code clear and easy to read?
public void createDatabase() throws SQLException, IOException {
SQLiteDatabase database = dbStore.getDatabase();
LineNumberReader scriptInputReader = new LineNumberReader(new InputStreamReader(getClass().getResourceAsStream(SCRIPT_CREATE)));
for(String line; (line = scriptInputReader.readLine()) != null;) {
database.execSQL(line);
}
}
I write a lot of “for” loops like the one above. For me it looks clear – it shows the temporary variable (“line”) used in the loop, limits it’s scope and points out when the loop ends (when “readLine” returns “null”). I wonder if other programmers will hate me for those…
or this one:
SQLiteDatabase database = dbStore.getDatabase();
Cursor cursor = database.query("PINS", new String [] {"ID", "X", "Y"}, null, null, null, null, "ID");
if(cursor.moveToFirst()) {
for(; !cursor.isAfterLast(); cursor.moveToNext()) {
(...)
}
}
cursor.close();
Are things like the above just “neat” or already a Java-puzzles?
I like what you’ve done, but I would make one small change:
This separates the iteration action from the loop termination condition. Also, unlike the “while” version, it limits the scope of the
linevariable to the loop – narrowing scope as much as possible is good coding practice.Also, code style checkers usually consider assignments nested within tests as “poor style”. To be clear, your code is a bit like this: