TIP: string concat

I still see sometimes very large concats of strings doing:

var str = “my " +
" string” +
" is" +
" great"

avoid this use the right way so that it will be 1 big string at compile time:

var str = “my
string
is
great”

This is way faster in developer because every + needs to be parsed.
But also in the clients that + is a waste, everytime that methods runs it needs to really do that concat, this will generate many temp strings that then are converted in 1 big string which is then also again garbage collected.
So it uses a lot more cpu power and memory.

thanks for the tip Johan!

One ‘heads-up’ with this tip.
Make sure you don’t have any spaces after your slash or else the parser won’t see this as a continues string.

Nice tip, something I will use more often.
Only downside of this notation is that the result string will have a lot of white spaces in it because of the code formatting. I notice this when I want to debug large sql statements, it makes formatting them in pgadmin a bit harder.

Hi Jos,

Just add \n’s to the SQL and you get even better debug code back as well (SQL error in line 3 of … instead of line 1[ i.e. the whole SQL]).
like so:

var _sQuery = "SELECT myColumn \n\
FROM myTable \n\
WHERE myOtherColumn='criteria' \n\
ORDER BY mySortColumn DESC";

thx for the tip Robert, that makes debugging a lot easier!

Also avoid concatenating strings with variables using templates—velocity, regexp, or simple micro template function.

var template = '<div class="product_box">\n\
		  <div class="product_bg">\n\
		    <div class="product_top">\n\
		      <div class="product_bottom">\n\
		        <div class="product_main"><a href="{{url}}"> <img src="{{resources}}{{picture}}" alt="" /></a>\n\
		          <div class="content">\n\
		            <h3>{{name}}</h3>\n\
		            <div class="product_text">\n\
		            	{{description}}\n\
		            	<p><a href="{{url}}">Click to order!</a></p>\n\
		            </div>\n\
		          </div>\n\
		          <span class="clear"></span> </div>\n\
		      </div>\n\
		    </div>\n\
		  </div>\n\
		</div>'
						
var data = { 	resources	: globals.CMS.markup.getSiteDirectory(),
				name		: product.product.product_name,
				picture		: product.pictures[0].search,
				description	: obj.block_data.description,
				url			: globals.CMS.token.getPage(page).link}

var html = globals.CMS.markup.merge(template,data)

most of the time what i see its not even concatenating for variables of dynamic values…
Its most of the time to get a readable string over multiply lines so not 1 big line…
"a few " + variable + “and go on
a bit more
and some " + variable2 + " is not
really a problem”

Or even simpler in your HTML case: no string concatenating, validation of the variables you use (so builder markers if you make a type, refactoring support, search support etc), no manual linebreaks to put in, no issues with forgetting a \ or having trailing spaces etc etc. and no logic to write to merge the variables in (or use 3rd party code to do so):

var data = {
	resources 	: globals.CMS.markup.getSiteDirectory(),
    name      	: product.product.product_name,
    picture     : product.pictures[0].search,
    description : obj.block_data.description,
    url         : globals.CMS.token.getPage(page).link
}

var template = <div class="product_box">
<div class="product_bg">
  <div class="product_top">
    <div class="product_bottom">
      <div class="product_main"><a href={data.url}> <img src={data.resources + data.picture} alt="" /></a>
        <div class="content">
          <h3>{data.name}</h3>
          <div class="product_text">
             {data.description}
             <p><a href={data.url}>Click to order!</a></p>
          </div>
        </div>
        <span class="clear"></span> </div>
    </div>
  </div>
</div>
</div>
          
var html = template.toXMLString()

Didn’t know you could template with xml. Definitely behaves better in Servoy’s editor for anything you can set up as a well formed xml object. I’ll be using this, good one.

pbakker:
Or even simpler in your HTML case: no string concatenating, validation of the variables you use (so builder markers if you make a type, refactoring support, search support etc), no manual linebreaks to put in, no issues with forgetting a \ or having trailing spaces etc etc. and no logic to write to merge the variables in (or use 3rd party code to do so):

var data = {
resources 	: globals.CMS.markup.getSiteDirectory(),
name      	: product.product.product_name,
picture     : product.pictures[0].search,
description : obj.block_data.description,
url         : globals.CMS.token.getPage(page).link

}

var template =

{data.name}

{data.description}

Click to order!

var html = template.toXMLString()

Nice, yes, for simple cases.
All well and good, but a bit too simplistic in most real life case/scenario… what happens when you need more than just inserting a few variable content?
Like adding conditions, formatting or loops to fill complex templates?
In that case, you use Velocity.

So instead of mixing all sorts of templating options and using one or the other, go for the one that will offer the best flexibility and power from the start, now guess which one it is? ;)

And once it’s there, you know that it will also add some horsepower to your Servoy install in lots of different areas as well like serving web sites, reporting, charting, web services, etc.

  • my $0.02

ptalbot:
All well and good, but a bit too simplistic in most real life case/scenario… what happens when you need more than just inserting a few variable content?
Like adding conditions, formatting or loops to fill complex templates?
In that case, you use Velocity.

In real life situations that require conditionals, formatting and loops—I prefer having a debugger. No way I want to do something like this server-side in a templating system:

var shippingOptions	= ''
for (var i = 0; i < checkout.shipping.details.length; i++) {
	var address 	= JSON.stringify(checkout.shipping.details[i])
	var template 	= '<option data-address={{address}} value="{{value}}" {{selected}}>{{display}}</option>\n'
	var data		= { value		: i + 1,
						display		: (i == ss) ? "Address " + (i + 1) + " (default)" : "Address " + (i + 1),
						selected	: (i == ss) ? 'selected="selected"' : null }
	shippingOptions += globals.CMS.markup.merge(template,data)			
}

var html = globals.CMS.markup.merge('<div class="contact_row cont_pad">\n\
	    		<div class="select">\n\
		        	<select name="address_selector">\n\
		        	{{options}}\n\
		       		</select>\n\
	     		</div>\n\
     		</div>\n', shippingOptions)

The sweet spot for templates (server-side) in my opinion is removing the need for concatenating strings—which I find make code very unsightly and hard to read—while keeping the all logic in server-side javascript.

Paul’s xml tip just makes the micro-template approach that much better. Besides the advantages he points out, Servoy’s code editor immediately flags malformed html/xml (like a missing closing ). And best of all, removing all the string continuations makes the code even easier to read. I love it.

That’s a good point. Debugger is good, for sure.
BTW, Have you looked at the details output of the Velocity servlet when an error occured? Or the velocity.log?

Now personally I like templates to be out of the code entirely, either in the database or better yet, on the file system.
This way I can tweak them in real time without the need to redeploy any code or restart anything (but still be able to use a versioning system): changes are there as soon as I’ve made them.

I guess every problem has it’s tools to get solved. I’ve been using the XML stuff in a lot of cases and the capabilities it has are quite sufficient.

But in some cases they might not be and then you go looking for something else and it might just be velocity.

Paul