Code refactoring and test fix