This post has some hints about avoiding bugs: hashnode.com/post/what-are-some-programming-habit…
There are also books on the topic, like Clean Code and Design Patterns. Experience also helps.
But don't expect to ever reach the point where you write everything perfectly on the first try.