Refactor to functional programming style