The Optimal Length of Contracts With Application to Outsourcing