Refactoring: extracting common pattern matching to function