refactor cleaner code with pattern matching