Why do so many novice programmers make the same, silly mistakes?
When answering questions on StackOverflow, we often see the same silly mistakes over and over. Some examples:
A loop that's meant to accumulate results (calculating a total, appending to an array/list, etc.), but the programmer puts the initialization of the accumulator variable inside the loop so it gets reset every iteration, rather than putting it before the loop.
A loop that's searching for something in a collection, and should report "not found" if it fails. The incorrect loop typically looks something like this pseudo-code:
for element in collection: if element matches criteria: report found or return value break else: report not found
The result of this is that they get lots of "not found" reports along the way, but they never figure out by themselves that they can use a variable to keep track of whether the target is found so they can report failure at the end. Yesterday I responded to a question where the programmer "solved" that problem by putting
break
in theelse
branch as well, so his loop didn't actually loop, it just checked the first element.I wrote a canonical question/answer for this problem: Searching array reports “not found” even though it's found.
Recursion without using a
return
statement when making the recursive call, as in Recursive function does not return specified value. (Maybe this doesn't really belong in the list, recursion is often a hard concept for many programmers to pick up.)
I'm not a professional CS teacher (I just play one on the Internet), so I don't get any personal interaction with beginning programmers. I just wonder why these same mistakes happen so often. Is there something conceptually difficult about these algorithms?
I've occasionally tried asking the questioners what was going through their head when they were writing the code, since the errors seem so obvious to me. They can never explain their thinking, usually just saying something like "I just started programming a week ago, I don't know what I'm doing." If I press, they just get defensive and think I'm undermining their intelligence; maybe I do have an underlying feeling that someone who can't get these simple things right doesn't have the requisite logical thinking that it takes to be a decent programmer.
I'm hoping that real educators might be able to satisfy my curiosity. I suspect most of them are self-taught, so I'm not sure if curriculum is to blame. Do educators see these same errors among their students?