Code refactored with unit tests