Using counter or constant for parameter position

Suppose that I have the following Java code:

int i = 0;

PreparedStatement statement = con.prepareStatement("SELECT * FROM table " +   
"WHERE field1 = ?, field2 = ?, field3 = ?...");

statement.set***(++i, fieldValue);

And there are like 14 fields like that.

Then we have another prepared statement, but this time we see this:

i = 0;
PreparedStatement otherPreparedStatement = con.prepareStatement("SELECT * FROM table " +   
    "WHERE field1 = ?, field2 = ?, field3 = ?...")

statement.set***(++i, fieldValue);

All of this in the same method.

We flagged this as error prone and we recommended that we should be using constants like this:

preparedStatement.set***(PARAMETER_X_INDEX, fieldValue);

Now, I know that having these many parameters is just bad, but I do not see a way to refactor to use less.

What observations can be said about the first code and about the recommendation?

12

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *