Reduce duplication in search code