Why is String Templating Better Than String Concatenation from an Engineering Perspective?
Posted
by
stephen
on Programmers
See other posts from Programmers
or by stephen
Published on 2014-05-28T21:33:26Z
Indexed on
2014/06/06
21:50 UTC
Read the original article
Hit count: 470
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"
...
}
© Programmers or respective owner