The question of code ownership should definitely come up before you begin any work, and putting it in a contract as Zaxo suggests is definitely a good idea. It's certainly ethical as long as you discuss it with the client beforehand, and it's a good business practice if the code you save proves worthwhile sometime down the road. On thing to keep in mind is that this is just another bargaining chip to be assigned a dollar value - how much is it worth to them to keep exclusive ownership of the code? What is the code worth to you?
Having done some similar work in the past, I'd say that the code can stay with the employer in exchange for you getting paid a bit extra than if the code had also gone with you. I've done a few projects in the past, and nearly every time when I get to the end of it I think "Hmmm. If I had just conceptualized my design in a slightly different way, this could have been much shorter/more powerful/easier to understand." While I expected this to happen less as I learned more things and matured as a programmer, it's actually happened more and more as my bag of tricks has grown. :)
Also, it's a very good idea to negotiate the right to put some of the code you write in your personal portfolio. As the linked thread demonstrates, those code samples can come in handy down the road.