Refactoring code structure to remove duplication

@zankich  could you please take a look?

also  @hunterboerner  :)