Reputation: 10016
I've been following along with the Intro to Android Apps MOOC on Udacity and have been learning a lot about good coding practices just by looking at the sample code from that course. However, today I found something a little bit puzzling:
// Third Step: Insert ContentValues into database and get a row ID back
long locationRowId;
locationRowId = db.insert(WeatherContract.LocationEntry.TABLE_NAME, null, testValues);
Why was locationRowId
declared on a separate line? It seems like it would be much cleaner to change the code above to
long locationRowId = db.insert(WeatherContract.LocationEntry.TABLE_NAME, null, testValues);
Is there a particular reason for including the extra step? Or can I safely use the single-line version.
Thanks
Upvotes: 4
Views: 402
Reputation: 1874
There is no difference between the two. The best practice that I can think of here is - Don't declare local variables before use.
If you declare local variables before it is required, it will increase the scope of the variable and it will also likely to increase the chances of errors.
There are cases where you have to declare the variables before it is used. The below is one such example.
String line = null;
while (( line = br.readLine()) != null) {
buff.append(line);
}
It is up to the place where you are declaring your variable but there are no hard and fast rule to be followed.
Upvotes: 2
Reputation: 7131
If you are declaring global variables then declare it in a different line. Which means Using same variable in different methods.If you are using a variable inside of the methods then no need to initiate in different line.
Upvotes: 0
Reputation: 673
It does not matter, becouse you are doing theese same operations. Both expressions are correct, but better looks the second one. Of course it depends on it what do you want and where. If you want to use some of them, use one. Do not mix them
Upvotes: 0
Reputation: 459
Yes you can safely use the single line version! As commented above in my opinion it is just your preference. There is neither a point for nor against doing it. BUT choose one option and use it consequently and do not switch between them to get a clean code ;-)
Upvotes: 2