Then make it better? What you describe is basically how I program. Probably how everyone programs. Eventually I learn how the thing works and can comeback to cleanup my exploration code. At first I copy stuff from Stack Overflow and where ever... then some times try out permutations of things till they work, but after I figure it out there are probably better, cleaner ways of doing it... I might come back years after, and clean stuff up. Its the process.
Make it work. Make it work better.