refactoring: remove duplicated code, add tests