Is this kind of string manipulation Ok?
public string Format { get { return string.Format("{0}{1}v{1}", LastManStanding ? "FFA " : string.Empty, m_Teams.PlayersPerTeam); } }
should I rather use a Str开发者_高级运维ingBuilder
?
I'm not really sure how wrong it's to conditionally format strings like that, rather than doing
public string Format
{
get
{
StringBuilder sb = new StringBuilder();
if(LastManStanding)
sb.Append("FFA ");
sb.Append(string.Format("{0}v{0}", m_Teams.PlayersPerTeam);
return sb.ToString();
}
}
For such small strings, what you are doing is fine.
Use StringBuilder
when you are dealing with thousands of concatenations and/or string formatting.
Side note:
Instead of:
sb.Append(string.Format("{0}v{0}", m_Teams.PlayersPerTeam));
You can do:
sb.AppendFormat("{0}v{0}", m_Teams.PlayersPerTeam);
Wrong, no. Readable? Meh
A little formatting can go a long way
public string Format
{
get
{
return string.Format("{0}{1}v{1}",
LastManStanding ? "FFA " : string.Empty,
m_Teams.PlayersPerTeam);
}
}
The first version is preferred in my opinion, it clearly expresses your intention and its much more concise and easy to read then the second, lengthy one. I would format it like this though:
public string Format
{
get
{
return string.Format("{0}{1}v{1}", LastManStanding ? "FFA " : string.Empty,
m_Teams.PlayersPerTeam);
}
}
StringBuilder is preferred if you're doing edits on long string, in this case you don't need it.
Agree with everyone - for such small string it is ok. Note that your rewrite with StringBuilder is worse since you use String.Format instead of StringBuilder.AppendFormat.
In your case using single format string to create resulting string is benificial if you ever decide to start localizing your program in other laguages - it is possible to pull formatting tring from resources, but it is very hard to make code with StringBuilder to respect all possible languages.
Actually there could be another side of the story not realted to using StringBuilder or String.Format. Some people/teams prefer not to use ? :
operator. Knowing why you were recommended to rewrite piece of code would help to target rewrite.
I'd separate the formatting logic for FFA and normal games:
public string Format
{
get
{
if(LastManStanding)
return string.Format("FFA {0}v{0}", m_Teams.PlayersPerTeam);
else
return string.Format("{0}v{0}", m_Teams.PlayersPerTeam);
}
}
It's much easier to read. And logically the format strings are separate too. It's quite likely that you'll change them separately, and I'm surprised you didn't. "FFA 2v2" doesn't make much sense to me.
精彩评论