I ran across some code during a code review that didn't seem right, but not sure the "best" way to change it. In looking for an a answer I found which is better, using a nullable or a boolean return+out parameter and Which is better, return value or out parameter? The latter had a answer with this comment that I generally agree with:
If you find yourself needing to return two things from an API then wrapping them up in a struct/class would be better than an out param."
Here is a representative sample of the code in question. It's part of a web application and basically loops through a character buffer and wants to translate "unprintable" characters to either a replacement character or string. To do this, the author of the Translate
method always returns a string and the caller has to convert back to a character array.
string character = Translate(value);开发者_JAVA技巧
if (character.Length == 1) {
writer.Write(character[0]);
} else {
writer.Write(character.ToCharArray());
}
public string Translate(char value) {
if (value <= '\u017F') {
return value.ToString();
}
switch (value) {
case '\u2117':
return '\u00A9'.ToString(); // copyright sign
case '\u211E':
return "Rx"; // prescription
// ... and lots more case statements
}
return value.ToString();
}
It seemed to me I have a couple options. Do I make the caller infer which char or string to use based on null or String.Empty values, or be explicit with an out bool? I don't want to new up and return a tuple object instance for every char that passes through this function, since that seems like a lot of object creation overhead and future garbage collection.
public string Translate(char value, out char newValue)
public void Translate(char value, out char? newCharValue, out string newStringValue)
public void Translate(char value, out bool useChar, out char newCharValue, out string newStringValue)
What about always returning a string (of length 0, 1, or many), and always calling writer.Write(string)
?
If you return a string why not use "\u00A9" instead of '\u00A9'.ToString()?
Are you expecting to use this Translate method stand-alone anywhere, or is it always going to be used for the purpose of writing one stream's data to another? How about passing the writer to the Translate method, and letting it call the appropriate writer.Write
method?
精彩评论