Test Driven Development or TDD is one approach that really helps in this aspect. TTD basically means you write failing tests before actually implementing the feature. Then you code up the feature to make the tests pass. Then you repeat the process for the next feature. TDD not only minimizes the possibility of bugs in your code, but it also makes you more confident on your code and its behavior.