Why is String Templating Better Than String Concatenation from an Engineering Perspective?
- by stephen
I once read (I think it was in "Programming Pearls") that one should use templates instead of building the string through the use of concatenation.
For example, consider the template below (using C# razor library)
<in a properties file>
Browser Capabilities
Type = @Model.Type
Name = @Model.Browser
Version = @Model.Version
Supports Frames = @Model.Frames
Supports Tables = @Model.Tables
Supports Cookies = @Model.Cookies
Supports VBScript = @Model.VBScript
Supports Java Applets = @Model.JavaApplets
Supports ActiveX Controls = @Model.ActiveXControls
and later, in a separate code file
private void Button1_Click(object sender, System.EventArgs e)
{
BrowserInfoTemplate = Properties.Resources.browserInfoTemplate; // see above
string browserInfo = RazorEngine.Razor.Parse(BrowserInfoTemplate, browser);
...
}
From a software engineering perspective, how is this better than an equivalent string concatentation, like below:
private void Button1_Click(object sender, System.EventArgs e)
{
System.Web.HttpBrowserCapabilities browser = Request.Browser;
string s = "Browser Capabilities\n"
+ "Type = " + browser.Type + "\n"
+ "Name = " + browser.Browser + "\n"
+ "Version = " + browser.Version + "\n"
+ "Supports Frames = " + browser.Frames + "\n"
+ "Supports Tables = " + browser.Tables + "\n"
+ "Supports Cookies = " + browser.Cookies + "\n"
+ "Supports VBScript = " + browser.VBScript + "\n"
+ "Supports JavaScript = " +
browser.EcmaScriptVersion.ToString() + "\n"
+ "Supports Java Applets = " + browser.JavaApplets + "\n"
+ "Supports ActiveX Controls = " + browser.ActiveXControls
+ "\n"
...
}