refactor logic to methods and remove keep_if