Refactoring and handling bad cases