Factor out util method and write some unit tests.