If you look at programming as a knowledge acquisition activity instead of a code production activity, then you couldn't possibly have implemented it that way in the first place.
Exactly. Usually I don't have (or give myself) the luxury, but when I'm working on something small and I don't really have time constraints for it, I will write it, then rewrite it, then look at it from a different angle, and rewrite it again. Only after about three rewrites will I get something that looks good.
I'd like to bring this down to writing something good looking earlier, but it's like you say - I only learned it then and there.