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 Capabilitiesn"
+ "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"
...
}
13
The engineering principles at play here are readability and DRY.
The primary driver of readability is length. Shorter code is more readable (for readers of adequate skill level), so the first case reads better.
A secondary driver is clutter. The absence of punctuation and extraneous characters favours the first case.
The DRY point here is that symbols such as browser
and n
are concealed in the abstraction in case 1, and repeated in case 2. If either of those needed to be changed there would be less places to change in case 1 than case 2.
Set against this is WYSIWYG. In the first case there is something missing between the code you see and how it is put to work, where in the second case all the machinery is plain to see.
[At the opinion level, I would strongly favour case 1; others would not. But that would make this an opinion-based question and it might get closed, so we wouldn’t want to venture there.]
1