CodeSOD: A Matter of Understanding
For years, Victoria had a co-worker who "programmed by Google Search"; they didn't understand how anything worked, they simply plugged their problem into Google search and then copy/pasted and edited until they got code that worked. For this developer, I'm sure ChatGPT has been a godsend, but this code predates its wide use. It's pure "Googlesauce".
StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("SELECT * FROM TABLE1 WHERE COLUMN1 = 1 WITH UR"); String sqlStr = stringBuffer.toString(); ps = getConnection().prepareStatement(sqlStr); ps.setInt(1, code); rs = ps.executeQuery(); while (rs.next()) { count++; }
The core of this WTF isn't anything special- instead of running a SELECT COUNT they run a SELECT and then loop over the results to get the count. But it's all the little details in here which make it fun.
They start by using a StringBuffer to construct their query- not a horrible plan when the query is long, but this is just a single, simple, one-line query. The query contains a WITH clause, but it's in the wrong spot. Then they prepareStatement it, which does nothing, since this query doesn't contain any parameters (and also, isn't syntactically valid). Once it's prepared, they set the non-existent parameter 1 to a value- this operation will throw an exception because there are no parameters in the query.
Finally, they loop across the results to count.
The real WTF is that this code ended up in the code base, somehow. The developer said, "Yes, this seems good, I'll check in this non-functional blob that I definitely don't understand," and then there were no protections in place to keep that from happening. Now it falls to more competent developers, like Victoria, to clean up after this co-worker.
[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!