2011-02-10 48 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) { ... }