ResultSet rs = pstatement.executeQuery();
boolean flag = false;
if (rs.next()) {
if ("Y".equalsIgnoreCase(rs.getString(1)))
;
{
flag = true;
}
}
if (flag) {
// do something
}
How many problems can you find in the above code? I can think of a few.
The egregious issue is the stray semicolon after the condition check. Add two more brackets and it should become obvious what the issue is.
ResultSet rs = pstatement.executeQuery();
boolean flag = false;
if (rs.next()) {
if ("Y".equalsIgnoreCase(rs.getString(2))) {
;
}
{
flag = true;
}
}
if (flag) {
// do something
}
The semicolon is treated as a no-op and the conditional check treats that statement as to what should be executed if the condition is true. Because of this flag will always be set to true. I'm assuming that the developer intended that the flag only be set to true if the condition is true, but that is not what is happening.
The second issue may not cause a problem right away, but could easily cause an issue if the SQL query is changed in the future. Relying on the order of columns brought back by a query makes the code less readable and therefore more prone to future errors. Lets assume that the original query is something like:
select EMP_ID, ACTIVE_FLAG from employees;
If someone comes along in the future and decides that we also need to retrieve the department number like so:
select EMP_ID, DEPT_NO, ACTIVE_FLAG from employees;
and changes the query, but forgets to change the index on the rs.getString(2), then we are going to have a big issue.
Rather than using the column index, it is preferable to use the column name:
rs.getString("ACTIVE_FLAG");
Another big issue is that multiple rows could be returned by the ResultSet, but the code assumes that we are only interested in the first row.
The hard-coded "Y" and bad variable name of 'flag' are also bad practices, but not as bad as the above.