Refactoring grid search