user11125276
user11125276

Reputation:

Using the DRY principle for functions with different return values and types

Say I have two methods

public int findPages() {
    return this.selectors
        .getPagesSelector()
        .map(selector -> {
            Elements htmlElement = this.htmlPage.select(selector);
            return NumberUtils.toInt(htmlElement.text(), 1);
        })
        .orElse(1);
}
private String findPercent(Element product, double oldPrice, double newPrice) {
    return this.selectors
        .getPercentSelector()
        .map(selector -> {
            Elements htmlElement = product.select(selector);
            return StringUtils.defaultIfEmpty(htmlElement.text(), calculatePercent(oldPrice, newPrice));
        })
        .orElse(calculatePercent(oldPrice, newPrice));

The two do separate things and return different types but share code structures. Should I refactor the methods into a more abstract one for the sake of cleaner code, or is this not a violation of the DRY principle? Thanks!

Upvotes: 2

Views: 697

Answers (1)

Lajos Arpad
Lajos Arpad

Reputation: 76943

The DRY (Don't Repeat Yourself) principle, as its name suggests is about not having several implementations of the same thing. You have two methods, findPages and findPercent. In their totality, these two methods are doing very different things, so they are not repetitive with one-another. So we look for partial matches, however, if we look at the code, we see some differences, so it is not really a partial match either. One is calling the pagesSelector, the other is calling the percentSelector. You could do some refactorization, like a method which would get a name of selector and return the correct selector, but this would be a large and complicated work, which is not worth doing unless you have a very good reason and for such a large work and small gain, having two similar-looking codes is not a valid reason. If you had to write this kind of code maybe 100 times, then it would make sense to either refactor your code or write a code generator and generate your methods with that.

Upvotes: 2

Related Questions