2011-02-10 31 views
4

我正在創建一個需要打印HTML字符串和HTML文檔的打印機類。所以基本上可以得到:發送HTML參數和文件路徑參數?

Printer.Print("<b>Hello world</b>"); 

而且

Printer.Print(@"C:\hello.html"); 
設計我的課,我下面之間作出決定的打印方法定義

所以:

public static void Print(string inputString, string mode){ 
    if(mode=="htmlString"){//Print the string itself} 
    else if(mode=="htmlFile"){//Print the document in the filepath} 
} 

或者

public static void Print(string inputString){ 
    if(file.Exists(inputString)){//Print the document in the filepath} 
    else{//Print the string itself} 
} 

一般來說,這是t他更好的練習?第一個選項需要另一個不太好的參數,但如果我們使用第二個選項,如果打算實際打印文件但使用不正確的文件名,則會打印錯誤的內容。

+1

建築外牆的用戶可以關注一下聰明,但它可以變得非常混亂構建做幾不同的事情的方法,而他們的名字都不告訴你關於他們做什麼的一切。在這種情況下,打印一個簡單的字符串並打開和關閉一個文件會有很大的差異(和影響)。首先,包含文件名純文本的HTML如何?在你的示例中,我不能打印一個簡單的filePath作爲字符串。 – 2011-02-10 18:36:29

+0

好點,我從這個角度沒有想到太多。 – sooprise 2011-02-10 18:38:09

回答

5

很多時候有太多的意外空間,特別是在這種情況下,你必須確定如何根據輸入行爲,然後進一步做驗證處理(即File.Exists),它的哭了出於誤報。在我看來,做這樣的事情,而不是:

public static void PrintString(string input) 
{ 
    //print the string, knowing precisely this is the intent, 
    //and if not, it's what you're going to do anyway! 
} 

public static void PrintFile(string fileName) 
{ 
    //no qualms here, you're going to print a file 
} 
1

我建議你去先生失望先生建議的設計。

但是,如果因爲任何原因你想保留原來的想法,我會稍作改動。而不是像字符串那樣傳遞模式,而是將其作爲枚舉傳遞。事實上,你可以將失望先生的建議引入這一點。例如

​​

你的第二個想法是一個好主意,因爲你會被執行不必要的文件系統檢查每當用戶在打印原始字符串。更重要的是,它可能會引發異常,因爲在打印原始字符串時,這不會是有效的文件路徑。所以Exists檢查可能會炸燬。

0

我同意使用兩種方法是最好的方法。但是,.NET約定將具有以下方法名稱:

public static void Print(string path) { ... } 
public static void PrintHtml(string html) { ... }