[英]Java: separate main logic & exception-handling logic
問題: 如何將所有邏輯轉移到策略(另一個類),但將異常處理邏輯留給類所有者?
我有:方法map
,它從輸入參數獲取data
數組,然后對此執行很多邏輯:
class Owner ...
public void map(final LongWritable key, final Text value, final Context context) {
// 1st-fragment of code
String[] data = null;
try { // Not Owner class logic, should be moved to strategy
StringReader reader = new StringReader(line);
CustomParser cParser = new CustomParser(reader,_strategy);
data = cParser.getLine();
} catch (final IOException e) {
outputBadData(line); // Owner class logic
return;
}
// 2nd-fragment of code: logic which is based on `data` array
................
................
}
我想要:實際上1st
片段中的所有邏輯( outputBadData
除外)都不屬於此類。 我想提出戰略。 它看起來像:
public void map(final LongWritable key, final Text value, final Context context) {
// 1st-fragment of code
String[] data = strategy.getData(value);
// 2nd-fragment of code: logic which is based on `data` array
................
................
}
問題: outputBadData
是Owner
類的邏輯,而不是策略。
如果我理解正確,則必須創建Strategy類並在其中定義具有所需邏輯的方法。 在此方法的簽名中定義“引發IOException”
例如:
public [return type] readLine(arguments...) throws IOException {
...
}
同樣,您必須具有對新類(策略)的對象的引用,才能調用“ readLine”方法。 您可以將該對象存儲為Owner類的字段,並在創建此類的實例時將其作為構造函數參數傳遞(用於使用setter方法)。 然后,在Owner類的'map'方法中,用'try-catch'塊包圍'readLine'方法調用以處理異常:
try{
strategyReference.readLine(arguments...);
}catch (IOException e) {
outputBadData(line);
return;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.