This is personal preference and there are many ways it can be done. I like to keep my templates as clean as possible and use get_template_part() to include the various parts.
For parts of code that is used often I like to create functions and call the functions in the templates.