The optimal length of contracts with application to outsourcing