Refactor the code and add test case