<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>scriptNode &#187; code-style</title>
	<atom:link href="http://scriptnode.com/tag/code-style/feed/" rel="self" type="application/rss+xml" />
	<link>http://scriptnode.com</link>
	<description>Tips and tricks for web developers.</description>
	<lastBuildDate>Tue, 01 Sep 2009 18:46:41 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>PHP: goto hell;</title>
		<link>http://scriptnode.com/article/php-goto-hell/</link>
		<comments>http://scriptnode.com/article/php-goto-hell/#comments</comments>
		<pubDate>Fri, 14 Aug 2009 19:53:11 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Novice]]></category>
		<category><![CDATA[code-style]]></category>
		<category><![CDATA[just-for-fun]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=326</guid>
		<description><![CDATA[
As of version 5.3, PHP supports goto (much to the chagrin of many). To protest, one snarky programmer filed a faux bug in their bug tracking system:





Funny stuff! But all kidding aside, I personally feel like PHP was ugly enough without goto. To me, one of the language&#8217;s biggest downfalls has always been that it [...]]]></description>
			<content:encoded><![CDATA[<p>
As of <a href="http://www.sitepoint.com/article/whats-new-php-5-3/">version 5.3</a>, PHP supports <a href="http://us3.php.net/goto"><code>goto</code></a> (much to the chagrin of many). To protest, one snarky programmer filed a <a href="http://bugs.php.net/bug.php?id=48669">faux bug</a> in their bug tracking system:
</p>
<p>
<a href="http://bugs.php.net/bug.php?id=48669"><img alt="PHP: goto hell;" src="/assets/img/php_goto_hell.jpg" style="border: 1px solid #000;"/></a>
</p>
<p>
Funny stuff! But all kidding aside, I personally feel like PHP was ugly enough without <code>goto</code>. To me, one of the language&#8217;s biggest downfalls has always been that it practically <em>encourages</em> sloppy design, and this is a huge step in the wrong direction. How do you feel about it?
</p>
<p>
(Link via <a href="http://foohack.com/">Isaac Schlueter</a>)</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/php-goto-hell/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Spacius! Source Code</title>
		<link>http://scriptnode.com/article/spacius-source-code/</link>
		<comments>http://scriptnode.com/article/spacius-source-code/#comments</comments>
		<pubDate>Tue, 10 Mar 2009 05:52:23 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[code-style]]></category>
		<category><![CDATA[games]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[just-for-fun]]></category>
		<category><![CDATA[lab]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=278</guid>
		<description><![CDATA[
I&#8217;ve been meaning to &#8220;release&#8221; this for quite some time now, but I wanted to do it in small doses, with in-depth explanations of the code. Making a game can be somewhat overwhelming, but it&#8217;s just like any other large task: if you break it up into smaller pieces, it becomes much easier to manage.


But [...]]]></description>
			<content:encoded><![CDATA[<p>
I&#8217;ve been meaning to &#8220;release&#8221; this for quite some time now, but I wanted to do it in small doses, with in-depth explanations of the code. Making a game can be somewhat overwhelming, but it&#8217;s just like any other large task: if you break it up into smaller pieces, it becomes much easier to manage.
</p>
<p>
But time is a commodity nowadays. I&#8217;ve got way less time to write, and when I do, I&#8217;d rather be writing <em>code</em> than tutorials (or honestly, <a href="http://raptr.com/richtaur"><em>playing</em> video games</a>). Sorry about that, but I hope the (well-commented!) source will help those of you out there who&#8217;d like to contribute to the <a href="http://games.nihilogic.dk/">slowly growing world of DHTML games</a>.
</p>
<p>
You&#8217;ll notice that this code is <a href="/article/spacius-a-space-adventure/">over 6 months old</a>. And I&#8217;m the kind of developer who constantly updates his <a href="/tag/code-style/">style, methods and patterns</a>. Given that, there may very well be many mistakes or bad practices in here, some of which I may have improved upon by now, but others maybe not. Either way, feel free to comment on them, and I&#8217;ll answer any questions as well.
</p>
<p>
Thanks for checking it out, and please be good to it. I&#8217;d love to know about any projects created with this source as a basis, and would appreciate links back here. Also please don&#8217;t claim it as your own, that&#8217;s not cool.
</p>
<div class="section">
For now I am hosting the source code with <a href="http://github.com/richtaur/spacius-/tree/master">GitHub</a>.
</div>
<p>
Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/spacius-source-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Common PHP Equivalents in JavaScript</title>
		<link>http://scriptnode.com/article/common-php-equivalents-in-javascript/</link>
		<comments>http://scriptnode.com/article/common-php-equivalents-in-javascript/#comments</comments>
		<pubDate>Sat, 03 Jan 2009 09:04:45 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[code-style]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=245</guid>
		<description><![CDATA[
It&#8217;s pretty widely known in the web development industry that server-side scripting is important, and PHP is an extremely common choice. Indeed, for many programmers it&#8217;s even  their first language. It&#8217;s quite common for web devs to begin on the server, then later require some client-side interaction, at which point they must turn to [...]]]></description>
			<content:encoded><![CDATA[<p>
It&#8217;s pretty widely known in the web development industry that server-side scripting is important, and <a href="http://us3.php.net/" title="PHP Hypertext Preprocessor">PHP</a> is an extremely common choice. Indeed, for many programmers <a href="http://reidburke.com/2008/10/05/when-php-is-your-first-language/">it&#8217;s even  their first language</a>. It&#8217;s quite common for web devs to begin on the server, then later require some client-side interaction, at which point they must turn to <a href="/tag/javascript/">JavaScript</a>.
</p>
<p>
I often see questions similar to, &#8220;I&#8217;ve got these few lines of PHP code, how would I do this in JavaScript?&#8221; I&#8217;ve actually <a href="/article/javascript-print_r-or-var_dump-equivalent/">already answered</a> a question like this, but I kept getting more questions, so I thought I&#8217;d cover many at once:
</p>
<ul>
<li><a href="#array-push">Pushing to an array</a></li>
<li><a href="#die"><code>die()</code> or <code>exit</code></a></li>
<li><a href="#include"><code>include</code> or <code>require</code></a></li>
<li><a href="#redirection">Redirection</a></li>
<li><a href="#static-classes">Static classes</a></li>
<li><a href="#strings">String manipulation</a></li>
</ul>
<h3 id="array-push">Pushing to an array</h3>
<p>
Pushing a new value to the end of an array is a common, trivial task. Here&#8217;s some PHP to accomplish this:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
$my_array = array();<br />
$my_array[] = &#8216;a&#8217;;<br />
array_push($my_array, &#8216;b&#8217;);<br />
</textarea></p>
<p>
Also note this quick pointer from php.net&#8217;s <a href="http://us3.php.net/manual/en/function.array-push.php"><code>array_push()</code> documentation</a>:
</p>
<blockquote><p>If you use <code>array_push()</code> to add one element to the array it&#8217;s better to use <code>$array[] =</code> because in that way there is no overhead of calling a function.</p>
</blockquote>
<p>
This isn&#8217;t the case in JavaScript. The native <code>Array.push</code> method is most optimal:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
var myArray = [];<br />
myArray.push(&#8217;a'); // This is the way to go<br />
myArray[myArray.length] = &#8216;b&#8217;; // This method is possible but bad<br />
</textarea></p>
<h3 id="die"><code>die()</code> or <code>exit</code></h3>
<p>
There has been much confusion regarding what JavaScript is and how it works in the browser. When looking for an equivalent to <code>exit</code>, one probably doesn&#8217;t understand that client-side JavaScript is a behavioral language that&#8217;s intended to react to events. In PHP, a script executes, stopping only when told to do so, and then it&#8217;s done. JavaScript lives and breathes on the page, reacting to the mouse being moved, keys being pressed and even time changing.
</p>
<p>
So it&#8217;s important to understand why this is not a fair equivalent, and that even asking for one shows a misunderstanding. That said, a bit of procedural JavaScript can be exited by using an anonymous function. Here&#8217;s some example PHP and then similar code in JavaScript:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
if ($next_action == &#8216;exit&#8217;) {<br />
	exit;<br />
}</p>
<p>echo &#8216;Made it here!&#8217;;<br />
</textarea></p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
(function() {</p>
<p>	if (nextAction == &#8216;exit&#8217;) {<br />
		return;<br />
	}</p>
<p>	alert(&#8217;Made it here!&#8217;);</p>
<p>})();<br />
</textarea></p>
<p>
While the language behavior is not one-to-one, taking advantage of JavaScript&#8217;s closure already has advantages, among them being able to easily exit a function via <code>return</code>.
</p>
<h3 id="include"><code>include</code> or <code>require</code></h3>
<p>
There have been some arguments about this equivalence in JavaScript. Just like the previous example, this equivalence is not one-to-one and should be thought about in very different terms. That said, here is a quick example of including a PHP file within a PHP script:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
// Nothing to it, just include the file:<br />
include(&#8217;my_file.php&#8217;);</p>
<p>// This code will only execute after my_file.php has been included:<br />
echo &#8216;File included!&#8217;;<br />
</textarea></p>
<p>
To include an external script in JavaScript, writing a method or including a library is definitely best. <a href="/article/dynamically-load-css-and-js-files/">I wrote about this once</a>, but there are libraries such as <a href="http://developer.yahoo.com/yui/" title="Yahoo! User Interface library">YUI</a> that have <a href="http://developer.yahoo.com/yui/get/">better support with more options</a>. Here&#8217;s what this would look like using YUI:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
// Call YUI&#8217;s method<br />
var objTransaction = YAHOO.util.Get.script(&#8221;http://example.com/my_file.js&#8221;, {<br />
	// This function will only fire after my-file.js has been included:<br />
	onSuccess : function() {<br />
		alert(&#8221;File included!&#8221;);<br />
	}<br />
});<br />
</textarea></p>
<h3 id="redirection">Redirection</h3>
<p>
This one is easy and straightforward. A redirect is accomplished with <a href="http://us3.php.net/manual/en/function.header.php">PHP&#8217;s <code>header()</code> function</a>:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
header(&#8217;Location: http://example.com&#8217;);<br />
exit; // Not necessary but a good practice<br />
</textarea></p>
<p>
Also very simple in JavaScript:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
location.href = &#8216;http://example.com&#8217;;<br />
</textarea></p>
<h3 id="static-classes">Static classes</h3>
<p>
In PHP, it&#8217;s a pretty common programming pattern to use a static class for encapsulation, sort of namespacing some methods and properties. Here&#8217;s an example:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
class Tools {</p>
<p>    public static function check_stuff() {<br />
        return true;<br />
    }</p>
<p>}</p>
<p>echo Tools::check_stuff();<br />
</textarea></p>
<p>
For this JavaScript equivalence, it probably makes the most sense to use an object literal:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
Tools = {<br />
	checkStuff : function() {<br />
		return true;<br />
	}<br />
};</p>
<p>alert(Tools.checkStuff());<br />
</textarea></p>
<h3 id="strings">String manipulation</h3>
<p>
String manipulation is absolutely mandatory in most applications. Fortunately, it&#8217;s a breeze thanks to <a href="http://us3.php.net/manual/en/ref.strings.php">PHP&#8217;s fantastic string functions</a>:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
// Replace portions within a string<br />
echo str_replace(&#8217;Hey&#8217;, &#8216;Hi&#8217;, &#8216;Hey there&#8217;); // outputs &#8220;Hi there&#8221;</p>
<p>// Capitalization<br />
echo strtolower(&#8217;Hey there&#8217;); // outputs &#8220;hey there&#8221;<br />
echo strtoupper(&#8217;Hey there&#8217;); // outputs &#8220;HEY THERE&#8221;</p>
<p>// Get a portion of a string<br />
echo substr(&#8217;Hey there&#8217;, 0, 2); // outputs &#8220;He&#8221;</p>
<p>// Get rid of extraneous whitespace<br />
echo trim(&#8217;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Hey there&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8217;); // outputs &#8220;Hey there&#8221;<br />
</textarea></p>
<p>
<a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String" title="Mozilla's String reference">Each of these</a> have perfect equivalents except for <code>trim()</code>, which we need to implement ourselves:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
// Replace portions within a string<br />
alert(&#8217;Hey there&#8217;.replace(&#8217;Hey&#8217;, &#8216;Hi&#8217;)); // outputs &#8220;Hi there&#8221;</p>
<p>// Capitalization<br />
alert(&#8217;Hey there&#8217;.toLowerCase()); // outputs &#8220;hey there&#8221;<br />
alert(&#8217;Hey there&#8217;.toUpperCase()); // outputs &#8220;HEY THERE&#8221;</p>
<p>// Get a portion of a string<br />
alert(&#8217;Hey there&#8217;.substr(0, 2)); // outputs &#8220;He&#8221;</p>
<p>// Get rid of extraneous whitespace<br />
trim = function(txt) {<br />
	return txt.replace(/^\s+|\s+$/g, &#8221;);<br />
};</p>
<p>alert(trim(&#8217;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Hey there&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8217;)); // outputs &#8220;Hey there&#8221;</p>
<p></textarea></p>
<p>
Or, we can augment the <code>String</code> global so that strings will have this method natively:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
String.prototype.trim = function() {<br />
	return this.replace(/^\s+|\s+$/g, &#8221;);<br />
};</p>
<p>// Get rid of extraneous whitespace<br />
alert(&#8217;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Hey there&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8217;.trim()); // outputs &#8220;Hey there&#8221;<br />
</textarea></p>
<p>
While not all of these equivalents are smooth (or even recommended), it&#8217;s typically helpful when learning a new language to have it compared to a language one is already familiar with. If you can think of any other common PHP tasks that have relatively similar equivalents in JavaScript, please let me know in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/common-php-equivalents-in-javascript/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>PHP to Use Backslash as Namespace Separator</title>
		<link>http://scriptnode.com/article/php-to-use-backslash-as-namespace-separator/</link>
		<comments>http://scriptnode.com/article/php-to-use-backslash-as-namespace-separator/#comments</comments>
		<pubDate>Sun, 26 Oct 2008 21:23:52 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Novice]]></category>
		<category><![CDATA[code-style]]></category>
		<category><![CDATA[news]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=235</guid>
		<description><![CDATA[
After much debate, the minds behind PHP have made an important decision. The good news is, PHP will support namespaces. The (arguably) bad news is, the namespace separator will be the backslash character.


Here&#8217;s a simple example of what this will look like:


$object_instance = new My\PEAR\Module(&#8217;myvar&#8217;);


PHP 5 already already has its criticisms. The developers looked at [...]]]></description>
			<content:encoded><![CDATA[<p>
After <a href="http://wiki.php.net/_media/rfc/php.ns.txt?id=rfc%3Anamespaceseparator&#038;cache=cache">much debate</a>, the minds behind <a href="http://php.net/">PHP</a> have made an important decision. The good news is, PHP will support namespaces. The (arguably) bad news is, <a href="http://news.php.net/php.internals/41374">the namespace separator will be the backslash character</a>.
</p>
<p>
Here&#8217;s a simple example of what this will look like:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
$object_instance = new My\PEAR\Module(&#8217;myvar&#8217;);<br />
</textarea></p>
<p>
PHP 5 already already has <a href="http://www.tnx.nl/php5.html">its criticisms</a>. The developers looked at <a href="http://wiki.php.net/rfc/namespaceseparator">many different options</a>, including <code>**</code>, <code>^^</code>, <code>%%</code>, <code>:&gt;</code>, <code>:)</code> and <code>:::</code>, but eventually decided on <code>&#92;</code>, which is an odd decision, given that it doesn&#8217;t remotely resemble <a href="http://www.math.tu-berlin.de/polymake/index.html#perl/namespaces.html[3,3,0]">its</a> <a href="http://en.wikipedia.org/wiki/Namespace_identifier">cousins</a>. In fact, it most closely resembles <a href="http://en.wikipedia.org/wiki/MS-DOS">directories in MS-DOS</a> or <a href="http://en.wikipedia.org/wiki/Windows_Registry">other Windows features</a>.
</p>
<p>
The argument was also made that current operators such as  <code>::</code> or <code>-&gt;</code> could have been used, but they <a href="http://us2.php.net/manual/en/language.oop5.paamayim-nekudotayim.php">already had other duties</a>. The argument doesn&#8217;t go far, however, because PHP of course uses the backslash character for escaping.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/php-to-use-backslash-as-namespace-separator/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Multiline Strings in JavaScript</title>
		<link>http://scriptnode.com/article/multiline-strings-in-javascript/</link>
		<comments>http://scriptnode.com/article/multiline-strings-in-javascript/#comments</comments>
		<pubDate>Wed, 22 Oct 2008 00:17:48 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[code-style]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[lab]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=217</guid>
		<description><![CDATA[
The ability to write multiline strings is a common feature in many languages. It promotes readability and is often much cleaner than the alternatives. Here&#8217;s a typically ugly example of string concatenation in PHP:


$my_string = &#8220;This string\n&#8221;;
$my_string .= &#8220;spans multiple\n&#8221;;
$my_string .= &#8220;lines.\n&#8221;;


Thankfully, PHP has the benefit of heredoc syntax, which makes code like this much [...]]]></description>
			<content:encoded><![CDATA[<p>
The ability to write multiline strings is a common feature in many languages. It promotes readability and is often much cleaner than the alternatives. Here&#8217;s a typically ugly example of string concatenation in <a href="http://us2.php.net/" title="PHP Hypertext Preprocessor">PHP</a>:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
$my_string = &#8220;This string\n&#8221;;<br />
$my_string .= &#8220;spans multiple\n&#8221;;<br />
$my_string .= &#8220;lines.\n&#8221;;<br />
</textarea></p>
<p>
Thankfully, PHP has the benefit of <a href="http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc">heredoc syntax</a>, which makes code like this much easier to read, write and maintain:
</p>
<p><textarea class="php" cols="50" id="heredoc-example" name="code" rows="10"><br />
$my_string = &lt;&lt;&lt;MYSTRING<br />
This string<br />
spans multiple<br />
lines.<br />
MYSTRING;<br />
</textarea></p>
<h3>E4X</h3>
<p>
But what about <a href="http://developer.mozilla.org/en/JavaScript">JavaScript</a>? There is no native heredoc support, but there are some other workarounds that can be used. The first I&#8217;ll offer up is <a href="http://en.wikipedia.org/wiki/E4X">ECMAScript for XML (E4X)</a>.
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
var myString = &#8221; + &lt;myString&gt;&lt;![CDATA[This string<br />
spans multiple<br />
lines.<br />
]]&gt;&lt;/myString&gt;;<br />
</textarea></p>
<p>
The first line in the above example is a bit confusing. The <acronym title="Extensible Markup Language">XML</acronym> will return an xml object by default, but what we want is a <code>String</code>. We can type the return as a <code>String</code> by concatenating to an empty string (<code>''</code>).
</p>
<p>
Next, an element must be wrapped around the <code>CDATA</code> to trigger the <acronym>XML</acronym> parser. This step is similar to PHP&#8217;s <a href="#heredoc-example">heredoc syntax</a> in that it requires an identical beginning and ending identifier.
</p>
<p>
You can test this yourself <a href="/lab/e4x/">in the lab</a>.<br />
Currently, it looks like only <a href="http://developer.mozilla.org/En/Gecko">Gecko</a> browsers (such as <a href="http://www.mozilla.com/en-US/firefox/">Firefox</a> and <a href="http://caminobrowser.org/">Camino</a>) support E4X. This obviously doesn&#8217;t include <a href="http://browsehappy.com/why/">Internet Explorer</a>, which is (unfortunately) often a large portion of most websites&#8217; user bases. While this workaround is interesting, it&#8217;s definitely not realistic to assume all of your users are using Firefox, <a href="http://xkcd.com/111/">despite its rising popularity</a> (also, it will <a href="http://tr.im/hez">fail to validate</a>).
</p>
<h3>Hidden Element Hack</h3>
<p>
Another workaround I&#8217;ve seen is to place the string inside of an element (often hidden from view) and to read it in via JavaScript. Here&#8217;s an example:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
/* Based on this markup:<br />
&lt;div id=&#8221;multilines&#8221; style=&#8221;display: none;&#8221;&gt;<br />
This string<br />
spans multiple<br />
lines.<br />
&lt;/div&gt;<br />
*/<br />
var myString = document.getElementById(&#8217;multilines&#8217;);<br />
</textarea></p>
<p>
This solution is clever, but definitely a hack job: not very clean, and with a bad <a href="http://www.w3.org/WAI/intro/accessibility.php">accessibility case</a>. The primary issue though is that it doesn&#8217;t completely solve the problem. Markup is needed to interact with the JavaScript code, so to use this solution one couldn&#8217;t maintain a completely independent <code>.js</code> file.
</p>
<h3>Escaping linebreaks</h3>
<p>
Another solution is very simply just to escape line breaks:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
var myString = &#8220;This string\<br />
spans multiple\<br />
lines.&#8221;;<br />
</textarea></p>
<p>
By escaping the linebreak, you&#8217;re free to continue the string on the next line (<em><strong>note:</strong> this doesn&#8217;t include spaces, so if you want to separate words, you&#8217;ll need to begin each new line with a space</em>). This solution is not as attractive as the E4X workaround, but has the benefit of being perfectly cross-browser compatible. Therefore, it looks like it&#8217;s currently the best method available.
</p>
<p>
Do you know of any other workarounds? If so, please let me know in the comments section.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/multiline-strings-in-javascript/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Evaluating Script Tags Dynamically</title>
		<link>http://scriptnode.com/article/evaluating-script-tags-dynamically/</link>
		<comments>http://scriptnode.com/article/evaluating-script-tags-dynamically/#comments</comments>
		<pubDate>Sun, 21 Sep 2008 08:00:30 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[code-style]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[script-sunday]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=142</guid>
		<description><![CDATA[
First, a disclaimer: dynamically evaluating scripts is not recommended! Indeed, if your application requires the usage of this script, chances are you&#8217;re doing it wrong. The separation of design and logic likely hasn&#8217;t been properly enforced if you&#8217;re using this method. It&#8217;s just an awkward use-case that should be avoided. That said, here it is&#8230;


Many [...]]]></description>
			<content:encoded><![CDATA[<p>
First, a disclaimer: <strong>dynamically evaluating scripts is not recommended!</strong> Indeed, if your application requires the usage of this script, chances are <em>you&#8217;re doing it wrong</em>. The separation of design and logic likely hasn&#8217;t been properly enforced if you&#8217;re using this method. It&#8217;s just an awkward use-case that should be avoided. That said, here it is&#8230;
</p>
<p>
Many JavaScript libraries support the evaluating of data returned via <a href="http://www.w3.org/TR/XMLHttpRequest/" title="XML Http Request">XHR</a>. Some, like <a href="http://developer.yahoo.com/yui/">YUI</a>, do not (yet). In other cases, folks have rolled their own <a href="http://en.wikipedia.org/wiki/List_of_Ajax_frameworks">&#8220;<acronym title="Asynchronous JavaScript and XML">AJAX</acronym> library&#8221;</a> but still want this behavior. The below script supports searching <acronym title="Hypertext Markup Language">HTML</acronym> for scripts and evaluating them:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
/**<br />
 * Evaluate the passed content for &lt;script&gt; tags<br />
 * @param {String} html The string to parse<br />
 */<br />
var evalHTML = function(html) {</p>
<p>	var piece,<br />
		res = html.split(/&lt;script/);</p>
<p>	res.shift();</p>
<p>	for (var i = 0, len = res.length; i &lt; len; i++) {</p>
<p>		(piece = res[i].split(/&gt;/)).shift();</p>
<p>		try {<br />
			eval(piece.join(&#8217;>').split(&#8217;&lt;/scr&#8217; + &#8216;ipt&gt;&#8217;).shift());<br />
		} catch (e) {}</p>
<p>	}</p>
<p>};<br />
</textarea></p>
<p>You can execute some examples yourself below:</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
// Example 1 &#8211; script inside of a div<br />
evalHTML(&#8217;&lt;div&gt;&lt;scr&#8217; +<br />
&#8216;ipt&gt;alert(&#8221;Hello, JavaScript!&#8221;);&lt;/scr&#8217; +<br />
&#8216;ipt&gt;&#8217;);<br />
</textarea></p>
<p>
<button id="example-eval-1">Execute example 1</button>
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
// Example 2 &#8211; script sets a global variable then displays it<br />
evalHTML(&#8217;&lt;scr&#8217; + &#8216;ipt&gt;var foo = &#8220;bar&#8221;;&lt;/scr&#8217; +&#8217;ipt&gt;&#8217; +<br />
&#8216;&lt;scr&#8217; + &#8216;ipt&gt;alert(foo);&lt;/scr&#8217; +&#8217;ipt&gt;&#8217;);<br />
</textarea></p>
<p>
<button id="example-eval-2">Execute example 2</button>
</p>
<p><script type="text/javascript">
<!--//
var evalHTML=function(html){var piece,res=html.split(/<script/);res.shift();for(var i=0,len=res.length;i<len;i++){(piece=res[i].split(/>/)).shift();try{eval(piece.join(">").split("<\/script>").shift())}catch(e){}}};</p>
<p>YAHOO.util.Event.addListener('example-eval-1', 'click', function() {
evalHTML('
<div><scr' + 
'ipt>alert("Hello, JavaScript!");</scr' +
'ipt>');
});</p>
<p>YAHOO.util.Event.addListener('example-eval-2', 'click', function() {
evalHTML('<scr' + 'ipt>var foo = "bar";</scr' +'ipt>' +
'<scr' + 'ipt>alert(foo);</scr' +'ipt>');
});</p>
<p>//-->
</script></p>
<ul class="download">
<li><a href="/assets/js/dynamic-eval/eval.js">[Download eval.js]</a> (376 bytes)</li>
<li><a href="/assets/js/dynamic-eval/eval-min.js">[Download eval-min.js]</a> (214 bytes; compressed)</li>
</ul>
<p>
<strong>Update 9/28/08:</strong> Fixed a bug thanks to <a href="http://foohack.com/">Isaac Schlueter</a> (see <a href="/article/evaluating-script-tags-dynamically/#comment-197">comments</a>).</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/evaluating-script-tags-dynamically/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Quickly Update DocumentRoot in Apache2</title>
		<link>http://scriptnode.com/article/quickly-update-documentroot-in-apache2/</link>
		<comments>http://scriptnode.com/article/quickly-update-documentroot-in-apache2/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 19:33:50 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[code-style]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[script-sunday]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=63</guid>
		<description><![CDATA[
For today&#8217;s Script Sunday I thought I&#8217;d take a go back in time a little and provide an old utility that I still to this day find useful.
It&#8217;s a script I wrote called ChangeLocalHost which alters the DocumentRoot in apache2. An example of its use would be:


./clh.php local-site.com/public_html/


Note: you must be root to run it


Given [...]]]></description>
			<content:encoded><![CDATA[<p>
For today&#8217;s <a href="/tag/script-sunday/">Script Sunday</a> I thought I&#8217;d take a go back in time a little and provide an old utility that I still to this day find useful.<br />
It&#8217;s a script I wrote called <code>ChangeLocalHost</code> which alters the <code>DocumentRoot</code> in <code>apache2</code>. An example of its use would be:
</p>
<p>
<code>./clh.php local-site.com/public_html/</code>
</p>
<p>
<em>Note: you must be <code>root</code> to run it</em>
</p>
<p>
Given this command, the script will change <code>DocumentRoot</code> to <strong>local-site.com/public_html/</strong> and restart <code>apache2</code>.<br />
I work on <a href="http://dirtybeta.com/">a lot</a> of <a href="http://valadria.com/">websites</a> (developing most of them on my laptop running <code>apache2</code>)<br />
so I use this script constantly.
</p>
<p>
Here&#8217;s the code:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
#!/usr/bin/php<br />
&lt;?php</p>
<p>/*<br />
ChangeLocalHost v0.1 &#8211; last updated Mar 07 2007<br />
Must be root to execute. Alters the DocumentRoot in Apache2&#8217;s conf file, then restarts Apache2.<br />
*/</p>
<p>$obj_clh = new ChangeLocalHost(&#8217;/etc/apache2/sites-available/&#8217;, &#8216;default&#8217;, &#8216;/home/www/&#8217;);</p>
<p>$obj_clh-&gt;setArgs($_SERVER['argv']);<br />
$obj_clh-&gt;run();</p>
<p>/**<br />
 * CLH class constructor<br />
 * @constructor<br />
 */<br />
class ChangeLocalHost {</p>
<p>	private $arr_args,<br />
			$bit_msgs,<br />
			$str_dir,<br />
			$str_file,<br />
			$str_pre;</p>
<p>	protected $str_version;</p>
<p>	/**<br />
	 * Constructor method<br />
	 * @param string str_dir The location of the Apache conf file to mod<br />
	 * @param string str_file The name of the Apache conf file to mod<br />
	 * @param string str_pre The needle to search for in the conf file<br />
	 */<br />
	function __construct($str_dir, $str_file, $str_pre) {</p>
<p>		$this-&gt;str_version = &#8216;ChangeLocalHost v0.1&#8242;;</p>
<p>		$this-&gt;arr_args = Array();<br />
		$this-&gt;bit_msgs = true;<br />
		$this-&gt;str_dir  = $str_dir;<br />
		$this-&gt;str_file = $str_file;<br />
		$this-&gt;str_pre  = $str_pre;</p>
<p>	}</p>
<p>	/**<br />
	 * Modify Apache&#8217;s DocumentRoot<br />
	 * @param string str_file The (conf) file to mod<br />
	 * @param string str_new_dir The new directory to set as DocumentRoot<br />
	 * @private<br />
	 */<br />
	private function alterLocalHost($str_file, $str_new_dir) {</p>
<p>		$str_contents = file_get_contents($str_file);</p>
<p>		if (!$str_contents) {<br />
			$this-&gt;showError(&#8217;Could not read &#8216; . $str_file);<br />
		}</p>
<p>		$int_begin    = strpos($str_contents, $this-&gt;str_pre);<br />
		$int_end      = strpos(substr($str_contents, $int_begin), &#8220;\n&#8221;);<br />
		$str_search   = substr($str_contents, $int_begin, $int_end);<br />
		$str_contents = str_replace($str_search, $str_new_dir, $str_contents);<br />
		$bit_written  = file_put_contents($str_file, $str_contents);</p>
<p>		if ($bit_written) {<br />
			$this-&gt;showMessage(&#8217;Successfully set DocumentRoot to &#8216; . $str_new_dir);<br />
		} else {<br />
			$this-&gt;showError(&#8217;Could not write &#8216; . $str_file);<br />
		}</p>
<p>	}</p>
<p>	/**<br />
	 * Validates the new directory to set<br />
	 * @param string str_new_dir The potential new directory<br />
	 * @private<br />
	 */<br />
	private function checkLocalHost($str_new_dir) {</p>
<p>		$str_set_to = $this-&gt;str_pre . $str_new_dir;</p>
<p>		if (is_dir($str_set_to)) {</p>
<p>			$this-&gt;setLocalHost($str_set_to);<br />
			$this-&gt;restartApache2();</p>
<p>		} else {<br />
			$this-&gt;showError($str_set_to . &#8216; is not a valid directory.&#8217;);<br />
		}</p>
<p>	}</p>
<p>	/**<br />
	 * Ensures this app is being executed as root<br />
	 * @private<br />
	 */<br />
	private function checkRoot() {</p>
<p>		// Make sure user is root<br />
		$str_command = &#8216;whoami&#8217;;</p>
<p>		exec($str_command, $arr_output, $int_return);</p>
<p>		if ($arr_output[0] != &#8216;root&#8217;) {<br />
			$this-&gt;showError(&#8217;You must be root to run this program.&#8217;);<br />
		}</p>
<p>	}</p>
<p>	/**<br />
	 * Makes a backup of the Apache conf file<br />
	 * @param string str_source The original to copy<br />
	 * @param string str_new The location of the backup<br />
	 * @return bool Whether the copy was successful or not<br />
	 * @private<br />
	 */<br />
	private function makeCopy($str_source, $str_new) {</p>
<p>		$bit_copy = copy($str_source, $str_new);</p>
<p>		if (!$bit_copy) {<br />
			$this-&gt;showError(&#8217;Could not make copy of &#8216; . $str_source);<br />
		}</p>
<p>		return true;</p>
<p>	}</p>
<p>	/**<br />
	 * Restarts Apache2<br />
	 * @private<br />
	 */<br />
	private function restartApache2() {</p>
<p>		$str_command = &#8216;apache2ctl restart&#8217;;</p>
<p>		exec($str_command, $arr_output, $int_return);</p>
<p>		if ($int_return &gt; 0) {<br />
			$this-&gt;showError(&#8217;Could not restart Apache2.&#8217; . $str_source);<br />
		}</p>
<p>		$this-&gt;showMessage(&#8217;Successfully restarted Apache2.&#8217;);</p>
<p>	}</p>
<p>	/**<br />
	 * Executes the script<br />
	 */<br />
	function run() {</p>
<p>		$this-&gt;checkRoot();</p>
<p>		$str_new_dir = $this-&gt;arr_args[1];</p>
<p>		switch ($this-&gt;arr_args[1]) {</p>
<p>			case &#8216;-c&#8217; :<br />
			case &#8216;&#8211;current&#8217; :<br />
				$this-&gt;showCurrent();<br />
				break;</p>
<p>			case &#8221; :<br />
			case &#8216;-h&#8217; :<br />
			case &#8216;&#8211;help&#8217; :<br />
				$this-&gt;showHelp();<br />
				break;</p>
<p>			case &#8216;-q&#8217; :<br />
			case &#8216;&#8211;quiet&#8217; :<br />
				$str_new_dir    = $this-&gt;arr_args[2];<br />
				$this-&gt;bit_msgs = false;<br />
				break;</p>
<p>			case &#8216;-v&#8217; :<br />
			case &#8216;&#8211;version&#8217; :<br />
				$this-&gt;showVersion();<br />
				break;</p>
<p>			default :<br />
				break;</p>
<p>		}</p>
<p>		$this-&gt;checkLocalHost($str_new_dir);<br />
		exit(0);</p>
<p>	}</p>
<p>	/**<br />
	 * Create a copy of the arguments global<br />
	 * @param array array_args The arguments to set<br />
	 */<br />
	function setArgs($arr_args) {<br />
		$this-&gt;arr_args = &amp;$arr_args;<br />
	}</p>
<p>	/**<br />
	 * Call the other methods to initiate the altering of the DocumentRoot<br />
	 * @param string str_new_dir The new value of DocumentRoot<br />
	 * @private<br />
	 */<br />
	private function setLocalHost($str_new_dir) {</p>
<p>		$str_ext    = &#8216;.bak&#8217;;<br />
		$str_file   = ($this-&gt;str_dir . $this-&gt;str_file);<br />
		$str_backup = $str_file . $str_ext;</p>
<p>		if (is_file($str_file)) {</p>
<p>			if ($this-&gt;makeCopy($str_file, $str_backup)) {<br />
				$this-&gt;showMessage(&#8217;Copied backup of &#8216; . $this-&gt;str_file . &#8216; to &#8216; . $this-&gt;str_file . $str_ext);<br />
			}</p>
<p>			$this-&gt;alterLocalHost($str_file, $str_new_dir);</p>
<p>		} else {<br />
			$this-&gt;showError($str_file . &#8216; cannot be found.&#8217;);<br />
		}</p>
<p>	}</p>
<p>	/**<br />
	 * Show what DocumentRoot is currently set to<br />
	 * @private<br />
	 */<br />
	private function showCurrent() {</p>
<p>		$str_file = ($this-&gt;str_dir . $this-&gt;str_file);</p>
<p>		if (is_file($str_file)) {</p>
<p>			$str_contents = file_get_contents($str_file);</p>
<p>			if (!$str_contents) {<br />
				$this-&gt;showError(&#8217;Could not read &#8216; . $str_file);<br />
			}</p>
<p>			$int_begin  = strpos($str_contents, $this-&gt;str_pre);<br />
			$int_end    = strpos(substr($str_contents, $int_begin), &#8220;\n&#8221;);<br />
			$str_search = substr($str_contents, $int_begin, $int_end);</p>
<p>			$this-&gt;showMessage(&#8217;The current DocumentRoot is: &#8216; . $str_search);<br />
			exit;</p>
<p>		} else {<br />
			$this-&gt;showError($str_file . &#8216; cannot be found.&#8217;);<br />
		}</p>
<p>	}</p>
<p>	/**<br />
	 * Display a message and exit<br />
	 * @param string str_error The message to display<br />
	 * @private<br />
	 */<br />
	private function showError($str_error) {</p>
<p>		echo &#8216;Error: &#8216; . $str_error . &#8220;\n&#8221;;</p>
<p>		exit(1);</p>
<p>	}</p>
<p>	/**<br />
	 * Show the help text and exit<br />
	 * @private<br />
	 */<br />
	private function showHelp() {</p>
<p>		$str_help .= &#8216;Usage: clh [DIRECTORY]&#8230; [OPTIONS]&#8216; . &#8220;\n&#8221;;<br />
		$str_help .= &#8216;Alter the DocumentRoot in Apache2.&#8217; . &#8220;\n&#8221;;<br />
		$str_help .= &#8220;\n&#8221;;<br />
		$str_help .= &#8216;  -c, &#8211;current  display current DocumentRoot and exit&#8217; . &#8220;\n&#8221;;<br />
		$str_help .= &#8216;  -h, &#8211;help     display this help and exit&#8217; . &#8220;\n&#8221;;<br />
		$str_help .= &#8216;  -q, &#8211;quiet    suppress most messages&#8217; . &#8220;\n&#8221;;<br />
		$str_help .= &#8216;  -v, &#8211;version  output version information and exit&#8217; . &#8220;\n&#8221;;<br />
		$str_help .= &#8220;\n&#8221;;<br />
		$str_help .= &#8216;Report bugs to &lt;scriptnode@gmail.com&gt;.&#8217; . &#8220;\n&#8221;; // Hahahaha</p>
<p>		echo $str_help;</p>
<p>		exit(0);</p>
<p>	}</p>
<p>	/**<br />
	 * Display a message to the user<br />
	 * @param string str_message The message to show<br />
	 * @private<br />
	 */<br />
	private function showMessage($str_message) {</p>
<p>		if ($this-&gt;bit_msgs) {<br />
			echo $str_message . &#8220;\n&#8221;;<br />
		}</p>
<p>	}</p>
<p>	/**<br />
	 * Attempt to be more like a real application by displaying the version<br />
	 * @private<br />
	 */<br />
	private function showVersion() {</p>
<p>		echo $this-&gt;str_version . &#8220;\n&#8221;;</p>
<p>		exit(0);</p>
<p>	}</p>
<p>}<br />
</textarea></p>
<p>
You&#8217;ll notice that the script is at least a year and a half old.<br />
Usually if code of mine is more than a year old, it&#8217;s completely unusuable because my <a href="/article/my-new-coding-habits/">habits change pretty often</a>.<br />
But I think I&#8217;ve finally gotten to that sweet spot where it&#8217;s not total garbage, it just needs tweaking.
</p>
<p>
I was surprised that the code isn&#8217;t too bad really. It&#8217;s easily readable and well organized. There are many things that I wouldn&#8217;t have done were I to write this again;<br />
for example, I stopped using type prefixes long ago (such as an array of users as <code>$arr_users</code>). I understand why I used to do this, but it&#8217;s not necessary<br />
and only clutters up the code.
</p>
<p>
Anyway, I find this script useful and I thought someone else might too. Enjoy!
</p>
<ul>
<li><a href="/assets/php/clh/clh.php.txt">[Download clh.php.txt]</a> (6,614 bytes)</li>
<li><a href="/assets/php/clh/clh.zip">[Download clh.zip]</a> (1,975 bytes)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/quickly-update-documentroot-in-apache2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>My New Coding Habits</title>
		<link>http://scriptnode.com/article/my-new-coding-habits/</link>
		<comments>http://scriptnode.com/article/my-new-coding-habits/#comments</comments>
		<pubDate>Sun, 03 Aug 2008 05:24:30 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Novice]]></category>
		<category><![CDATA[code-style]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=43</guid>
		<description><![CDATA[
I think any programmers worth their weight improve their practices and styles on a regular basis. I&#8217;ve noticed my code has changed drastically in the last year or so. It&#8217;s more organized, structured, and maintainable than it was, but I&#8217;ve also picked up what I think are some small but good changes:



No var in globals [...]]]></description>
			<content:encoded><![CDATA[<p>
I think any programmers worth their weight improve their practices and styles on a regular basis. I&#8217;ve noticed my code has changed <strong>drastically</strong> in the last year or so. It&#8217;s more organized, structured, and maintainable than it was, but I&#8217;ve also picked up what I think are some small but good changes:
</p>
<ol>
<li>
<h3>No <code>var</code> in globals (JavaScript)</h3>
<p>
I&#8217;d be lying if I said I <a href="http://yuiblog.com/blog/2008/04/16/global-domination-part-two/">wasn&#8217;t externally influenced</a> on this one. <a href="http://javascript.crockford.com/">Douglas Crockford</a> has a lot of great recommendations, and this is one I tend to agree with. When applicable and realistic, making your JavaScript code smaller is always a good thing. It means a faster download for your users which leads to a better user experience.
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
// Before:<br />
var scriptNode = {};</p>
<p>// After:<br />
scriptNode = {};<br />
</textarea>
</li>
<li>
<h3>Not abbreviating beyond readability</h3>
<p>
This is probably a lesson most programmers learned long ago. I went back to some of my older code recently, hoping to reuse it. The good news was that the code itself was written well enough that I could use it with minimal editing. The bad news was that I first had to figure out what many of the variables were for because they were so badly named:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
// Before:<br />
var setCoords = function(c, dir) {<br />
    var nc = {<br />
        x : c.x,<br />
        y : c.y<br />
    };<br />
    if (dir == &#8216;l&#8217;) {<br />
        nc.x&#8211;;<br />
    } else {<br />
        nc.x++;<br />
    }<br />
    return nc;<br />
};</p>
<p>// After:<br />
/**<br />
 * Set the coordinates based on direction<br />
 * @param {Object} coords An object with x/y keys<br />
 * @param {String} dir The direction [l, r]<br />
 * @return {Object} An x/y object with the new coordinates<br />
*/<br />
var setCoords = function(coords, dir) {<br />
    var newCoords = {<br />
        x : coords.x,<br />
        y : coords.y<br />
    };<br />
    if (dir == &#8216;l&#8217;) {<br />
        newCoords.x&#8211;;<br />
    } else {<br />
        newCoords.x++;<br />
    }<br />
    return newCoords;<br />
};<br />
</textarea></p>
<p>
I&#8217;m not suggesting <a href="http://en.wikipedia.org/wiki/Hungarian_notation">Hungarian notation</a>, but descriptive variable and function names are the way to go. You don&#8217;t want to hate yourself a month later (or for whoever is working with your code to hate you) when it needs to be maintained later. And thanks to tools like <a href="http://developer.yahoo.com/yui/compressor/">YUI Compressor</a>, even JavaScript files won&#8217;t be negatively affected by adding a few characters here and there.
</p>
</li>
<li>
<h3>CSS dashes instead of camelCase</h3>
<p>
The logic here is that a language should look like itself. I understand why I used to prefer camelCase; even minified CSS files can&#8217;t alter class names or IDs, so dashes make for a larger download. But when revisiting a file, it looks less alien when the nomenclature is cohesive. This makes everything easier.
</p>
<p><textarea class="css" cols="50" name="code" rows="10"><br />
/* Before: */<br />
.userOptions {<br />
    font-family: verdana, sans-serif;<br />
}<br />
div#mainCommentBubble {<br />
    background-image: url(bubble.gif);<br />
}</p>
<p>/* After: */<br />
.user-options {<br />
    font-family: verdana, sans-serif;<br />
}<br />
div#main-comment-bubble {<br />
    background-image: url(bubble.gif);<br />
}<br />
</textarea>
</li>
<li>
<h3>Leaning more towards <acronym title="Object Oriented">OO</acronym></h3>
<p>
Again, I think many programmers have learned this lesson already, and likewise I&#8217;ve been using these practices for a while now. The difference is that my code has become so much more maintainable that I preach these lessons often and have become something of an advocate of these patterns.
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
// Before:<br />
showError();<br />
toggleElement(content);<br />
hideError();</p>
<p>// After:<br />
error.show();<br />
content.toggle();<br />
error.hide();<br />
</textarea>
</li>
<li>
<h3>Clean, organized MySQL queries</h3>
<p>
Thoughout my entire programming career (more than four years now), I have constantly changed the way I organized MySQL queries in my PHP code. Recently I noticed that editing my older code was a pain in the ass, and I sought to change that. Adding a <code>WHERE</code> clause or an extra <code>SELECT</code> parameter should be an easy task, and the solution to me was to break each section into new lines, tabbing in the same manner that I did in my code blocks:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
// Much before:<br />
$qry = &#8217;select chats.*, users.username from chats, users where chats.room_id = &#8216; . $room_id . &#8216; and chats.user_id = users.user_id&#8217;;</p>
<p>// Before:<br />
$qry = sprintf(&#8217;SELECT chats.*, users.username<br />
FROM chats, users<br />
WHERE (chats.room_id = %s) AND (chats.user_id = users.user_id)&#8217;,<br />
$room_id);</p>
<p>// After:<br />
$qry = &#8221;<br />
    SELECT<br />
        chats.*,<br />
        users.username<br />
    FROM<br />
        chats,<br />
        users<br />
    WHERE<br />
        (chats.room_id = $room_id)<br />
        AND (chats.user_id = users.user_id)<br />
&#8220;;<br />
</textarea></p>
<li>
<h3>Using a Single Event Listener When Possible</h3>
<p>
<a href="http://www.quirksmode.org/js/introevents.html">Events</a> can be tricky. They can be the cause of <a href="http://javascript.crockford.com/memory/leak.html">memory leaks</a>, and having too many can bog browsers down. So when dealing with multiple instances of similar events, why not combine them? Events are not difficult to parse to figure out what happened to what:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
// Before:<br />
var handleClick = function(e) {<br />
    // Something useful here<br />
};</p>
<p>var el, container = document.createElement(&#8217;ul&#8217;);<br />
container.id = &#8216;container&#8217;;</p>
<p>for (var i = 0; i < 10; i++) {<br />
    el = document.createElement('li');<br />
    el.innerHTML = 'List item ' + i;<br />
    YAHOO.util.Event.addListener(el, 'click', handleClick);<br />
    container.appendChild(el);<br />
}</p>
<p>document.body.appendChild(container);</p>
<p>// After:<br />
var handleClick = function(e) {<br />
    var el = YAHOO.util.Event.getTarget(e);<br />
    if (el.nodeName == 'LI') {<br />
        // Something useful here<br />
    }<br />
};</p>
<p>var el, container = document.createElement('ul');<br />
container.id = 'container';</p>
<p>for (var i = 0; i < 10; i++) {<br />
    el = document.createElement('li');<br />
    el.innerHTML = 'List item ' + i;<br />
    container.appendChild(el);<br />
}</p>
<p>YAHOO.util.Event.addListener(container, 'click', handleClick);<br />
document.body.appendChild(container);<br />
</textarea>
</li>
</ul>
<p>
Small improvements like these can add up to make <strong>much</strong> better code. If you&#8217;re a developer and you haven&#8217;t noticed a positive change in your code in the last few months, I highly recommend reading up on useful patterns and practices.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/my-new-coding-habits/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>An &#8220;Accident&#8221; I Constantly See in PHP Scripts</title>
		<link>http://scriptnode.com/article/an-accident-i-constantly-see-in-php-scripts/</link>
		<comments>http://scriptnode.com/article/an-accident-i-constantly-see-in-php-scripts/#comments</comments>
		<pubDate>Tue, 29 Jul 2008 03:18:19 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Novice]]></category>
		<category><![CDATA[code-style]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=45</guid>
		<description><![CDATA[
It&#8217;s quite normal to have multiple engineers working on an individual file or files with conflicting styles. Preferences come into play that do not affect the code at all. For example, I don&#8217;t like the one-true-brace style:


if ($condition)
{
    my_function();
}


My braces stay on the same line as the conditional. But I understand that [...]]]></description>
			<content:encoded><![CDATA[<p>
It&#8217;s quite normal to have multiple engineers working on an individual file or files with conflicting styles. Preferences come into play that do not affect the code at all. For example, I don&#8217;t like the <strong>one-true-brace</strong> style:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
if ($condition)<br />
{<br />
    my_function();<br />
}<br />
</textarea></p>
<p>
<strong>My</strong> braces stay on the same line as the conditional. But I understand that it&#8217;s just preference, and that&#8217;s fine; the application behaves the same either way. If a file already uses this pattern for the most part, I will leave it alone and sometimes even code in that style to keep things cohesive. But there is a bad PHP habit that I&#8217;ve recently come to believe is a mistake, and will change when I see it:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
$first_name = &#8220;Jonny&#8221;;<br />
$last_name = &#8220;Chambers&#8221;;<br />
</textarea></p>
<p>
To me, this is accidental. These lines are parsed for variables, and when that feature isn&#8217;t being used, there&#8217;s an unnecessary performance hit happening. Granted, it&#8217;s a very <strong>nominal</strong> performance hit, but they can add up, and why suffer at all when there is no reason?
</p>
<p>
Don&#8217;t get me wrong: double quotes have their place, and I use them (properly) very frequently, such as:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
$user_id = 1;<br />
$sort = &#8216;username;<br />
$query = &#8220;SELECT * FROM users<br />
WHERE (user_id > $user_id)<br />
ORDER BY $sort&#8221;;<br />
</textarea></p>
<p>
Style is one thing, and intention is another. Some people prefer double quotes over single quotes, sure, but I think most engineers don&#8217;t <strong>intend</strong> to parse their strings twice every time, and so I often see using double quotes as a mistake.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/an-accident-i-constantly-see-in-php-scripts/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
