Code climate refactoring

Refactoring to reduce duplication and complexity.