Refactor duplication in gradient class