重构包含多个if条件的代码。

huangapple go评论66阅读模式
英文:

Refactoring code that contains multiple if conditions

问题

以下是已翻译的代码部分:

这是我编写的一些用于保存 UrlEntity 的代码

public UrlEntity saveUrlEntity(String longUrl, LocalDate dateAdded) {

    int urlLength = longUrl.length();
    if (urlLength >= Constants.MAX_LONG_URL_LENGTH) {
        throw new LongUrlLengthExceededException("URL with length " + urlLength + " exceeds the max length of " + Constants.MAX_LONG_URL_LENGTH + " characters");
    } else {

        List<UrlEntity> urlEntity = urlRepository.findByLongUrl(longUrl);
        if (urlEntity.size() > 0) {
            return urlEntity.get(0);
        } else {
            final String shortUrl = urlShorten.shortenURL(longUrl);
            if (urlRepository.findFirstByShortUrl(shortUrl).isPresent()) {
                logger.error("A short short URL collision occured for long URL: " + longUrl + " with generated short URL" + shortUrl);
                throw new ShortUrlCollisionException("A short URL collision occured");
            } else {
                logger.info("Shortened URL: " + shortUrl);

                final UrlEntity urlEntityToSave = new UrlEntity(dateAdded, longUrl, shortUrl);

                return urlRepository.save(urlEntityToSave);
            }
        }
    }
}

这是您进行的基本重构:

public UrlEntity saveUrlEntity(String longUrl, LocalDate dateAdded) {

    int urlLength = longUrl.length();
    if (urlLength >= Constants.MAX_LONG_URL_LENGTH) {
        throw new LongUrlLengthExceededException("URL with length " + urlLength + " exceeds the max length of " + Constants.MAX_LONG_URL_LENGTH + " characters");
    } else {
        List<UrlEntity> urlEntity = urlRepository.findByLongUrl(longUrl);
        if (urlEntity.size() > 0) {
            return urlEntity.get(0);
        } else {
            return saveUrlEntityValue(longUrl, dateAdded);
        }
    }
}

private UrlEntity saveUrlEntityValue(String longUrl, LocalDate dateAdded){
    final String shortUrl = urlShorten.shortenURL(longUrl);
    if (urlRepository.findFirstByShortUrl(shortUrl).isPresent()) {
        logger.error("A short short URL collision occured for long URL: " + longUrl + " with generated short URL" + shortUrl);
        throw new ShortUrlCollisionException("A short URL collision occured");
    } else {
        logger.info("Shortened URL: " + shortUrl);

        final UrlEntity urlEntityToSave = new UrlEntity(dateAdded, longUrl, shortUrl);

        return urlRepository.save(urlEntityToSave);
    }
}

这个重构并没有显著改善代码。是否有一种代码模式或典型的方法来重构 saveUrlEntity 方法?我正在使用 Java11

英文:

Here is some code I've written to save a UrlEntity :

public UrlEntity saveUrlEntity(String longUrl, LocalDate dateAdded) {

    int urlLength = longUrl.length();
    if (urlLength &gt;= Constants.MAX_LONG_URL_LENGTH) {
        throw new LongUrlLengthExceededException(&quot;URL with length &quot; + urlLength + &quot; exceeds the max length of &quot; + Constants.MAX_LONG_URL_LENGTH + &quot; characters&quot;);
    } else {

        List&lt;UrlEntity&gt; urlEntity = urlRepository.findByLongUrl(longUrl);
        if (urlEntity.size() &gt; 0) {
            return urlEntity.get(0);
        } else {
            final String shortUrl = urlShorten.shortenURL(longUrl);
            if (urlRepository.findFirstByShortUrl(shortUrl).isPresent()) {
                logger.error(&quot;A short short URL collision occured for long URL: &quot; + longUrl + &quot; with generated short URL&quot; + shortUrl);
                throw new ShortUrlCollisionException(&quot;A short URL collision occured&quot;);
            } else {
                logger.info(&quot;Shortened URL: &quot; + shortUrl);

                final UrlEntity urlEntityToSave = new UrlEntity(dateAdded, longUrl, shortUrl);

                return urlRepository.save(urlEntityToSave);
            }
        }
    }
}

The above code exists in a service class and looks unnecessarily complex. I'm attempting to refactor so that the intent is clear. This is a basic refactoring I've written:

public UrlEntity saveUrlEntity(String longUrl, LocalDate dateAdded) {

    int urlLength = longUrl.length();
    if (urlLength &gt;= Constants.MAX_LONG_URL_LENGTH) {
        throw new LongUrlLengthExceededException(&quot;URL with length &quot; + urlLength + &quot; exceeds the max length of &quot; + Constants.MAX_LONG_URL_LENGTH + &quot; characters&quot;);
    } else {
        List&lt;UrlEntity&gt; urlEntity = urlRepository.findByLongUrl(longUrl);
        if (urlEntity.size() &gt; 0) {
            return urlEntity.get(0);
        } else {
            return saveUrlEntityValue(longUrl, dateAdded);
        }
    }
}

private UrlEntity saveUrlEntityValue(String longUrl, LocalDate dateAdded){
    final String shortUrl = urlShorten.shortenURL(longUrl);
    if (urlRepository.findFirstByShortUrl(shortUrl).isPresent()) {
        logger.error(&quot;A short short URL collision occured for long URL: &quot; + longUrl + &quot; with generated short URL&quot; + shortUrl);
        throw new ShortUrlCollisionException(&quot;A short URL collision occured&quot;);
    } else {
        logger.info(&quot;Shortened URL: &quot; + shortUrl);

        final UrlEntity urlEntityToSave = new UrlEntity(dateAdded, longUrl, shortUrl);

        return urlRepository.save(urlEntityToSave);
    }
}

This refactoring does not improve the code substantially. Is there a code pattern or idiomatic way to refactor the method saveUrlEntity? I'm using Java11

答案1

得分: 2

这是非常主观的,但是... 由于您的大多数if语句都是保护/短路子句,其中涉及throwreturn,因此不需要使用else。我认为这个简单的改变可以使代码更易读。

public UrlEntity saveUrlEntity(String longUrl, LocalDate dateAdded) {

    final int urlLength = longUrl.length();
    if (urlLength >= Constants.MAX_LONG_URL_LENGTH) {
        throw new LongUrlLengthExceededException("URL with length " + urlLength + " exceeds the max length of " + Constants.MAX_LONG_URL_LENGTH + " characters");
    }

    final List<UrlEntity> urlEntity = urlRepository.findByLongUrl(longUrl);
    if (!urlEntity.isEmpty()) {
        return urlEntity.get(0);
    }

    final String shortUrl = urlShorten.shortenURL(longUrl);
    if (urlRepository.findFirstByShortUrl(shortUrl).isPresent()) {
        logger.error("A short short URL collision occured for long URL: " + longUrl + " with generated short URL" + shortUrl);
        throw new ShortUrlCollisionException("A short URL collision occured");
    }

    logger.info("Shortened URL: " + shortUrl);
    final UrlEntity urlEntityToSave = new UrlEntity(dateAdded, longUrl, shortUrl);
    return urlRepository.save(urlEntityToSave);
}

我还建议将urlEntity.size() > 0替换为!urlEntity.isEmpty()

这个方法似乎在做多件事情,违反了单一职责原则;您可能希望考虑更好地进行拆分。

英文:

This is very subjective, but... Since most of your if statements are guard/short-circuit clauses, which throw or return, there is no need to use else. I think this simple change makes the code much more readable.

public UrlEntity saveUrlEntity(String longUrl, LocalDate dateAdded) {

    final int urlLength = longUrl.length();
    if (urlLength &gt;= Constants.MAX_LONG_URL_LENGTH) {
        throw new LongUrlLengthExceededException(&quot;URL with length &quot; + urlLength + &quot; exceeds the max length of &quot; + Constants.MAX_LONG_URL_LENGTH + &quot; characters&quot;);
    }

    final List&lt;UrlEntity&gt; urlEntity = urlRepository.findByLongUrl(longUrl);
    if (urlEntity.size() &gt; 0) {
        return urlEntity.get(0);
    }

    final String shortUrl = urlShorten.shortenURL(longUrl);
    if (urlRepository.findFirstByShortUrl(shortUrl).isPresent()) {
        logger.error(&quot;A short short URL collision occured for long URL: &quot; + longUrl + &quot; with generated short URL&quot; + shortUrl);
        throw new ShortUrlCollisionException(&quot;A short URL collision occured&quot;);
    }

    logger.info(&quot;Shortened URL: &quot; + shortUrl);
    final UrlEntity urlEntityToSave = new UrlEntity(dateAdded, longUrl, shortUrl);
    return urlRepository.save(urlEntityToSave);
}

I'd also recommend replacing urlEntity.size() &gt; 0 with !urlEntity.isEmpty().

The method does seem to be doing several things, which violates the Single Responsibility Principle; you might want to think about breaking that out better.

答案2

得分: 1

如果您使用`throw new``return`,则不需要else条件因为方法在此处结束

public UrlEntity saveUrlEntity(String longUrl, LocalDate dateAdded) {

    int urlLength = longUrl.length();
    if (urlLength >= Constants.MAX_LONG_URL_LENGTH) {
        throw new LongUrlLengthExceededException("URL长度为 " + urlLength + " 超过了最大长度 " + Constants.MAX_LONG_URL_LENGTH + " 字符");
    }
    
    List<UrlEntity> urlEntity = urlRepository.findByLongUrl(longUrl);
    if (urlEntity.size() > 0) {
        return urlEntity.get(0);
    }
    
    final String shortUrl = urlShorten.shortenURL(longUrl);
    if (urlRepository.findFirstByShortUrl(shortUrl).isPresent()) {
        logger.error("为长URL发生了短短URL冲突:" + longUrl + " 生成的短URL为:" + shortUrl);
        throw new ShortUrlCollisionException("发生了短URL冲突");
    }
    
    logger.info("缩短的URL:" + shortUrl);
    final UrlEntity urlEntityToSave = new UrlEntity(dateAdded, longUrl, shortUrl);
    return urlRepository.save(urlEntityToSave);
}
英文:

If you use throw new or return you do not need the else condition because the method ends like

public UrlEntity saveUrlEntity(String longUrl, LocalDate dateAdded) {

    int urlLength = longUrl.length();
    if (urlLength &gt;= Constants.MAX_LONG_URL_LENGTH) {
        throw new LongUrlLengthExceededException(&quot;URL with length &quot; + urlLength + &quot; exceeds the max length of &quot; + Constants.MAX_LONG_URL_LENGTH + &quot; characters&quot;);
    }
    
    List&lt;UrlEntity&gt; urlEntity = urlRepository.findByLongUrl(longUrl);
    if (urlEntity.size() &gt; 0) {
        return urlEntity.get(0);
    }
    
    final String shortUrl = urlShorten.shortenURL(longUrl);
    if (urlRepository.findFirstByShortUrl(shortUrl).isPresent()) {
        logger.error(&quot;A short short URL collision occured for long URL: &quot; + longUrl + &quot; with generated short URL&quot; + shortUrl);
        throw new ShortUrlCollisionException(&quot;A short URL collision occured&quot;);
    }
    
    logger.info(&quot;Shortened URL: &quot; + shortUrl);
    final UrlEntity urlEntityToSave = new UrlEntity(dateAdded, longUrl, shortUrl);
    return urlRepository.save(urlEntityToSave);
}

huangapple
  • 本文由 发表于 2020年9月4日 02:52:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63729967.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定