As a personal habit I generally prefer to use string replace
and format
methods, along with string "patterns", in lieu of string concatenation and other methods in most languages I use (typically C# and Javascript).
For example, if I want to generate a URL with parameters (C#), I use:
string url = "page.aspx?id={id}&ref={ref}";
return url.Replace("{id}", id)
.Replace("{referrer}", referrer);
// could also be expressed as
return "page.aspx?id={id}&ref={ref}".Replace("{id}", id)
.Replace("{referrer}", referrer);
Instead of:
return "page.aspx?id=" + id + "&ref=" & referrer;
Or:
// StringBuilder is typically more efficient than string concatenation
StringBuiler sbUrl = new StringBuilder();
sbUrl.Append("page.aspx?");
sbUrl.AppendFormat("id={0}", id);
sbUrl.AppendFormat("ref={0}", referrer);
return sbUrl.ToString();
I do the same in Javascript:
function generateUrl(p1, p2) {
return "page.aspx?1={0}&2={1}".replace("{0}", p1)
.replace("{1}", p2);
}
The reason is I prefer the readability of the code, especially when large amounts of textual data must be processed, such as in the case of a form letter or e-mail:
// this would typically be stored in an XML or other configuration file as a "pattern"
string body = @"Dear {name}:<br />
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec aliquam blandit risus, quis imperdiet nibh congue quis.</p>
<p>Pellentesque ullamcorper malesuada ante, ac auctor felis feugiat id. Etiam id eros convallis nisi feugiat tincidunt. Phasellus fringilla erat eu tortor egestas volutpat. Vestibulum in odio lorem, quis fringilla sapien.</p>
<p>Sincerely,</p>
<p class='sig'>{from-name}</p>";
return body.Replace("{name}", name).Replace("{from-name}", fName);
My concern is, however, that my methods are generally inefficient and that there may be better, more standardized ways of doing this.
Thoughts?