Sending HTML arguments and file path arguments?

I am creating a printer class that will print both HTML lines and HTML documents. So basically this can happen:

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

and

 Printer.Print(@"C:\hello.html"); 

Therefore, when designing my class, I determine the definition of the printing method between the following:

 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} } 

or

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

Overall, which is better? The first option requires a different argument, which is small, but if we use the second option, if we intend to actually print the file, but use the wrong file name, it will print the wrong one.

+4
source share
3 answers

Many times there are too many possibilities for unforeseen circumstances, especially in this case, when you have to determine how to act on the basis of input and then perform validation processing (i.e. File.Exists), it calls for false positives. In my opinion, do something like this:

 public static void PrintString(string input) { //print the string, knowing precisely this is the intent, //and if not, it what you're going to do anyway! } public static void PrintFile(string fileName) { //no qualms here, you're going to print a file } 
+5
source

I would suggest that you go with the design suggested by Mr. Disappointment.

However, if for some reason you want to keep the original idea, I would change it a little. Instead of passing the mode as a string, pass it as enum. In fact, you could send an offer from Mr. Disappointment to this. for instance

 public enum PrintMode { File, Raw } public static void Print(string printData, PrintMode mode) { if(mode == PrintMode.Raw) { //Print the string itself } else if (mode == PrintMode.File) { //Print the document in the filepath } else { throw new ArgumentException("Invalid print mode specified"); } } public static void PrintString(string input) { Print(input, PrintMode.Raw); } public static void PrintFile(string input) { Print(input, PrintMode.File); } 

Your second idea is a bad idea, as you do unnecessary file system checks whenever a user prints an raw string. More importantly, this is likely to throw an exception, since when printing the original line, this will not be a valid file path. So the Exists check is likely to explode.

+1
source

I agree that the best approach is to use two methods. However, .Net conventions would have the following method names:

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

Source: https://habr.com/ru/post/1339254/


All Articles