以下是我为保存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
2条答案
按热度按时间fwzugrvs1#
这很主观,但是。。。因为你大部分时间
if
语句是保护/短路子句throw
或者return
,无需使用else
. 我认为这个简单的改变使代码更具可读性。我也建议更换
urlEntity.size() > 0
与!urlEntity.isEmpty()
.这种方法似乎确实在做几件事,这违反了单一责任原则;你也许应该好好考虑一下。
xhv8bpkk2#
如果你使用
throw new
或者return
您不需要else条件,因为方法的结尾是