It's just a question of craftmanship - and having the available time to spend on the pursuit of craftmanship (in the event that you are producing the work for a paying client).
What does craftmanship entail?
At a basic level:
- Clean and consistent writing style
- Adequate documentation
- (IMO) descriptive names for methods, variables and classes
At a higher level you encounter common design principles
using Test Driven Design methodologies can help keep your methods clean and focussed.
Once you start making well designed classes, you start thinking about making well designed applications- where you may begin to think about concepts like Design Patterns and Dependency Injection.
Having dropped a few buzzwords, acronyms and wiki links, however, it still comes down to the same things as any form of craftmanship:
Patience, perseverance and attention to detail.
Your interest in a piece of code may well tail off before it is "finished", or you may be too impatient to engage in TDD or writing adequate documentation.
A Craftsman will overcome these obstacles and ensure that all the i's are dotted and t's crossed.
in response to OP's comment:
If you are working in a commercial environment. you may find you are not given adequate time to apply your craft to it's full extent. IME this is a very common cause for poor quality code - it's hard to sell Unit tests and documentation as a ROI to the customer/MD.