我正在使用的代码库经常使用实例变量在各种简单方法之间共享数据。最初的开发人员坚持认为这要遵循Bob / Robert Martin叔叔在Clean Code书中所述的最佳实践:“功能的第一个规则是它们应该很小。” 和“函数的理想参数个数为零(尼拉度)。(...)参数很难。它们需要很大的概念力。”
一个例子:
public class SomeBusinessProcess {
@Inject private Router router;
@Inject private ServiceClient serviceClient;
@Inject private CryptoService cryptoService;
private byte[] encodedData;
private EncryptionInfo encryptionInfo;
private EncryptedObject payloadOfResponse;
private URI destinationURI;
public EncryptedResponse process(EncryptedRequest encryptedRequest) {
checkNotNull(encryptedRequest);
getEncodedData(encryptedRequest);
getEncryptionInfo();
getDestinationURI();
passRequestToServiceClient();
return cryptoService.encryptResponse(payloadOfResponse);
}
private void getEncodedData(EncryptedRequest encryptedRequest) {
encodedData = cryptoService.decryptRequest(encryptedRequest, byte[].class);
}
private void getEncryptionInfo() {
encryptionInfo = cryptoService.getEncryptionInfoForDefaultClient();
}
private void getDestinationURI() {
destinationURI = router.getDestination().getUri();
}
private void passRequestToServiceClient() {
payloadOfResponse = serviceClient.handle(destinationURI, encodedData, encryptionInfo);
}
}
我将使用局部变量将其重构为以下内容:
public class SomeBusinessProcess {
@Inject private Router router;
@Inject private ServiceClient serviceClient;
@Inject private CryptoService cryptoService;
public EncryptedResponse process(EncryptedRequest encryptedRequest) {
checkNotNull(encryptedRequest);
byte[] encodedData = cryptoService.decryptRequest(encryptedRequest, byte[].class);
EncryptionInfo encryptionInfo = cryptoService.getEncryptionInfoForDefaultClient();
URI destinationURI = router.getDestination().getUri();
EncryptedObject payloadOfResponse = serviceClient.handle(destinationURI, encodedData,
encryptionInfo);
return cryptoService.encryptResponse(payloadOfResponse);
}
}
它更短,消除了各种琐碎方法之间的隐式数据耦合,并将变量范围限制为所需的最小值。尽管有这些好处,但我仍然似乎无法说服原始开发人员这种重构是有必要的,因为它似乎与上述Bob叔叔的做法相矛盾。
因此,我的问题是:偏爱局部变量而不是实例变量的客观科学依据是什么?我似乎不太愿意把手指放在上面。我的直觉告诉我,隐藏的联轴器是不好的,狭窄的范围要比广泛的范围好。但是支持这一点的科学是什么?
相反,我可能忽略了这种重构的不利之处吗?