Write it. Refactor it. Write it from scratch again. Read back your code. Rewrite it. Write it again. Maybe now you finally understand what you're building.
Then write it again, rewrite it, and write it once more :D
I know it sounds excessive, but when you're solving a problem you generally don't even fully understand it the first (few) times around, and once you do fully understand the problem you generally haven't found the best fitting solution on the first few tries either.