I have this code:
public int Delete(int id)
{
string query = "DELETE FROM [table] WHERE [id] = @id";
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
using (SqlCommand sqlCommand = new SqlCommand(query, sqlConnection))
{
sqlCommand.Parameters.Add("id", SqlDbType.Int).Value = id;
sqlConnection.Open();
if ((id = sqlCommand.ExecuteNonQuery()) == 0)
throw new Exception("Not found.");
return id;
}
}
Is it OK to reuse parameter ID to store number of rows affected or should I rather declare new variable? What's generally better?
Developers spend much more time reading code than writing code. Thus, one of your primary objectives should be to write to code that is easy to read and easy to understand.
If I have to read your code and just skim over the last line, I get the (false) impression that your method returns some kind of identifier. It doesn't. It returns the number of rows deleted.
Using a different variable makes your code easier to read and does not have any performance penalties.
...
var rowsDeleted = sqlCommand.ExecuteNonQuery();
if (rowsDeleted == 0)
throw new Exception("Not found.");
return rowsDeleted;
It also makes your code more robust to changes: Imagine that you some day decide to use GUIDs instead of integer IDs, so you change the type of your parameter to Guid. What happens? A completely unrelated part of your code breaks and needs to be fixed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With