2010-06-26 24 views
0

我了一系列異常的消息:處理可變字符串格式的通用方法?

enum myEnum { 
    BASIC(1, "An error occurred"), 
    WITH_ERRORID(2, "Error id: {0}"), 
    DETAILED(3, "Problem in record {0} with index {1}"); 
}; 

我也是有記錄單,可重複使用的權威和拋出一個自定義異常:

public void throwException (myEnum message) { 
    log.addEntry(message); 
    throw new CustomException(message); 
} 

調用該方法是直截了當:

throwException (myEnum.DETAILED); 

我現在正在用最優雅的方式格式化字符串。我可以一個toString()方法添加到枚舉基於輸入數量來格式化字符串,並更改throwException接受一個字符串代替:

String msg = message.toString(variable); 
throwException (msg); 

String msg2 = message.toString(variable, otherVariable); 
throwException (msg2); 

String msg3 = message.toString(variable, otherVariable, nextVariable); 
throwException (msg3); 

雖然這工作,我想移動的在throwException()中重複toString調用。我正在考慮傳遞一個ArrayList throwException()。但是,我還要把這些檢查列表的大小之前,我格式化字符串:

if (list.size == 1) MessageFormat.format(message, list.get(0)); 
if (list.size == 2) MessageFormat.format(message, list.get(0), list.get(1)); 

是解決這個問題的一個更好的技術或者設計方法?

回答

2

由於您使用的是枚舉類型聲明,因此我假設您使用的是JSE 5或更高版本。

鑑於此,我會說你是解決問題的最佳途徑。這裏是我的版本的枚舉:

public enum myEnum { 
    BASIC(1, "An error occurred"), 
    WITH_ERRORID(2, "Error id: {0}"), 
    DETAILED(3, "Problem in record {0} with index {1}"); 
    private int key = 0; 
    private String format = null; 

    private myEnum(int aKey, String aFormat) { 
     this.key=aKey; 
     this.format=aFormat; 
    } 

    /** 
    * This will take whatever input you provide and use the enum instance format 
    * string to generate a message. 
    */ 
    public String getMessage(Object... someContents) { 
     return MessageFormat.format(this.format, someContents); 
    } 
} 

要使用這些修改,你需要對你的throwException一個微小的變化()實現:

public void throwException (myEnum message, String... errorContents) { 
    String formattedMessage = message.getMessage(errorContents); 
    log.addEntry(formattedMessage); 
    throw new CustomException(formattedMessage); 
} 

使用可變參數的符號意味着你可以通過零或更多相同類型的值,並且它們在被調用的代碼中被視爲一個數組。沒有參數?它被視爲零長度數組,並且不會發生格式化。

剩下的唯一困難是我看不到任何顯而易見的方式在編譯時提醒開發人員需要更多參數來填寫格式。如果您沒有通過myEnum.DETAILED傳遞錯誤詳細信息,則會返回您開始使用的格式。

你應該已經有了需要注入你的格式的字符串;現在你只需要將它們傳遞給throwException()方法。這看起來是一個選項?