I finally understand why many authors on the subject of programming look down on "clever" code.
I encountered a scenario like this in the wild, though I've changed the data to be about students and height:
The requirement was to display the heights of students in a school broken down by how many in each classroom belonged to a specific range of height. So, how many students in classroom A were there between 40 and 45 inches, and how many were there in classroom A between 46 and 50, and so on for each classroom.
The "clever" solution that was in use for this was to make a database query for each classroom asking for a count of students that had a particular height. For example, the results for classroom might be that there are 5 students who are 46 inches tall, 12 who are 53 inches tall, 3 who are 54 inches tall, 2 who are 57 inches tall, etc.
Then, the code would go through this list starting with the lowest number, find out which group that inch count belonged to (40-45, 46-50, 50-54?) and add it to a running sum for that group. After going through every classroom, we would know how many students were of certain heights broken down by classroom.
I say it's "clever" because it's certainly interesting. It's at the very least a strange way to handle a task like that.
The "proper" solution is of course to go directly to the database and ask for exactly what you need. SQL databases can handle things like that easily. The "correct" solution does in one query what the "clever" solution does in 1 query per classroom. Additionally, there isn't any post-processing needed; the data is pretty much ready to use in the frontend.
As I said in the beginning of the post, I now understand why those authors hated "clever" code. It's not that the code was clever - it's that any sufficiently clever solution has a very straightforward and simple alternative that works just as well, if not better.
Leave a Comment