gpt4 book ai didi

java - 当公共(public)代码有多个不兼容的返回类型时分解公共(public)代码

转载 作者:行者123 更新时间:2023-12-02 11:21:03 29 4
gpt4 key购买 nike

我刚刚在重构时偶然发现了一段奇怪的代码。它看起来像是分解出两个 readString() 方法的共同部分的候选者,只是它似乎是不可能的(这对我来说是一个令人毛骨悚然的脑筋急转弯):

private final StringBuilder readStringBuilder = new StringBuilder(128);

@Override
public String readString() throws IOException {
final int l = readInt();
if (l <= 0) {
switch (l) {
case -1: return null;
case 0: return "";
default: throw new IOException("invalid string length encoding: " + l);
}
}
readStringBuilder.setLength(0);
for (int i=0; i<l; ++i) {
readStringBuilder.append(readChar());
}
return readStringBuilder.toString();
}

@Override
public String readString(final StringCache cache) throws IOException {
final int l = readInt();
if (l <= 0) {
switch (l) {
case -1: return null;
case 0: return "";
default: throw new IOException("invalid string length encoding: " + l);
}
}
readStringBuilder.setLength(0);
for (int i=0; i<l; ++i) {
readStringBuilder.append(readChar());
}
return cache.get(readStringBuilder, readStringBuilder);
}

您会发现,这两种方法的功能几乎相同,方法体完全相同,除了 return 语句之外。但是由于存在提前终止退出,我找不到可以获取主体的方法签名 - 自然返回类型将是 StringBuilder,只有在提前终止情况下才会是 String...

有什么想法如何将主体分解为单独的方法吗? (请注意,空 StringBuilder 上的 toString() 会创建一个新字符串,而不是返回常量字符串文字)

编辑:StringCache 的定义是:

public interface StringCache {
public String get(final CharSequence charSeq, final CharSequence notFoundResult);
}

最佳答案

难道不能创建一个私有(private)方法来适本地填充 readStringBuilder 吗?

然后两个 readString() 方法都使用该方法,并对缓存执行 get() ,或者对缓存执行 toString() readStringBuilder

根据组合方法重构来考虑这一点是值得的,它的原则是:

Composed method says that each method should do one and only one thing

当您遵守这一点时,您的方法通常会变得可重用(可组合)。

What have I achieved by going through this refactoring exercise? .... now that I have small building blocks, method reuse becomes easier because now I can mix and match them

请参阅 Neil Ford 关于组合方法重构的文章 here 。另请参阅 Martin Fowler 的 ' extractMethod ' 重构。

关于java - 当公共(public)代码有多个不兼容的返回类型时分解公共(public)代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11632075/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com