Refactor pattern matching