Always have an inspiration for one! It can start of with an idea, a story, a thought, an experience, and naturally the melody will come by.
Or it can also work the other way round. You hum a tune and lay it out, and then create or relate a story out of it what you feel that melody or chord...