[英]Can I avoid repeating myself in this situation (Java)
if (openFile == null) {
new AppFileDialog().chooseFile("Save", appFrame);
}
if (openFile == null) {
return;
}
在這里,我需要檢查用戶是否已經選擇了一個文件。 如果沒有,他們會得到提示。 如果文件仍為null,則函數將返回而不保存。 問題是兩個相同的if語句,我可以避免嗎? 我非常認真地對待DRY,但同時KISS。 理想情況下,這兩者是相輔相成的,但在這種情況下,似乎它們是相互排斥的。
雖然我認為不同的結構會使問題更加明顯,但並不完全如此:
// If no file, give the user a chance to open one
if (openFile == null) {
new AppFileDialog().chooseFile("Save", appFrame);
// still no file, user must not want to do this
if (openFile == null) {
return;
}
}
把它放在一個循環中? 用戶選擇的文件永遠不應為null
但是你已經刪除了太多的代碼給出了具體的答案。 我所看到的只是兩張相同的支票,我會合並成一張,但我想你來這里是為了更多。
生病做的事情如下:
int tries = 0;
int maxTries = 3;
do {
openFile = new AppFileDialog().chooseFile("Save", appFrame);
if (openFile != null)
tries = maxTries;
tries++;
} while (tries < maxTries);
if (openFile == null)
return;
我會嘗試擺脫那種副作用(在chooseFile方法中設置openFile),因為它使代碼很難遵循。 你不能退貨嗎?
但它不會解決雙重空檢查。
它們實際上是不同的條件。 我認為你的意思是:
if (openFile == null) {
openFile = new AppFileDialog().chooseFile("Save", appFrame);
if (openFile == null) {
return;
}
}
這表明它們並不意味着相同的東西,但如果您希望添加更多條件(更多可以打開文件的方式,例如使用默認文件名,如果用戶自己不提供),則更優雅
不過我更喜歡:
openFile = getOpenFile()
if(openFile == null)
return;
public File getOpenFile() {
if(openFile == null)
openFile = new AppFileDialog().chooseFile("Save", appFrame);
return openFile;
}
這允許getOpenFile()方法完全控制openFile變量,從不從任何其他方法訪問openFile變量(可能除了closeFile()方法。我有時使用這個技巧,使一個“邏輯上私有”的變量只是一個耦合方法以減少復雜性。
您可以嘗試這樣的方法,但這假設chooseFile
將返回該文件。
if ((openFile == null ? new AppFileDialog().chooseFile("Save", appFrame) : openFile) == null)
return;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.