Refatoring and add unit test