This is a dumb mistake:
List<Foo> fooList = new List<Foo>();
Foo f = new Foo();
while (something.Read()) {
f.Fill(something.GetRecord());
fooList.Add(f);
}
Of course, I should instantiate a new Foo inside the loop.
Can a compiler detect this kind of mistake at compile time?
To naïve eyes it looks like it should be able to detect this behavior (filling a List with instances of the same object in a loop). It should then issue a warning like "You are filling a container with the same instance more than once.".
So, how naïve am I being? Do you know of a language where something like this exists?
Yes, this is possible.
However, I don't think a tool or compiler would warn about this themselves, so you'd have to use a tool which can be extended with your own analyses. For Java, FindBugs is such a tool. For C,C++, etc, gcc 4.5 will allow plugins for people to write their own extensions, and clang from LLVM is designed for this too. There is also Dehydra from Mozilla, again for C++. For MS languages, there is the Phoenix framework.
So the question is, how do you write this analysis? Thats a little more tricky, and depends on the tool. But basically:
So you could quite easily detect a call to List<>.append(x)
in a loop, where x can refer to only one object.