<?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>HEAVYWORKS &#187; Coding</title> <atom:link href="http://www.heavyworks.net/blog/category/coding/feed" rel="self" type="application/rss+xml" /><link>http://www.heavyworks.net</link> <description>Extreme Software Engineering</description> <lastBuildDate>Fri, 27 Aug 2010 01:55:58 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3</generator> <item><title>Better error handling</title><link>http://www.heavyworks.net/blog/posts/better-error-handling</link> <comments>http://www.heavyworks.net/blog/posts/better-error-handling#comments</comments> <pubDate>Tue, 20 Apr 2010 18:44:28 +0000</pubDate> <dc:creator>Jan Seidl</dc:creator> <category><![CDATA[Coding]]></category> <category><![CDATA[best practices]]></category> <category><![CDATA[c++]]></category> <category><![CDATA[error handling]]></category> <category><![CDATA[exceptions]]></category> <category><![CDATA[java]]></category> <category><![CDATA[php]]></category> <category><![CDATA[python]]></category> <guid
isPermaLink="false">http://www.heavyworks.net/?p=440</guid> <description><![CDATA[Error handling and reporting was always a thing that I knew I wasn&#8217;t doing it right. Leaded by PHP&#8217;s on-the-fly type casting I used to make functions just return false or null but that was not right because I was hurting the return-type integrity of them. Let&#8217;s assume we have a function that returns users [...]
No related posts.]]></description> <content:encoded><![CDATA[<p><img
src="http://www.heavyworks.net/wordpress/wp-content/uploads/catcher.jpg" alt="Baseball Catcher" title="Better error handling" width="635" height="255" class="aligncenter size-full wp-image-489" /><br
/> Error handling and reporting was always a thing that I knew I wasn&#8217;t doing it right. Leaded by <acronym
title="PHP: Hypertext Preprocessor">PHP</acronym>&#8217;s on-the-fly type casting I used to make functions just return <code>false</code> or <code>null</code> but that was not right because I was hurting the return-type integrity of them.<br
/> <span
id="more-440"></span><br
/> Let&#8217;s assume we have a function that returns users IDs. What to expect for return type? Integers! Hell yeah! But what if the requested user ID is not found? Would you return <code>false</code>, <code>null</code>? Wrong!</p><p>In strict languages like C/C++ or Java, you can&#8217;t return a boolean in an integer function and so on. <acronym
title="PHP: Hypertext Preprocessor">PHP</acronym> gives the coder this &#8220;freedom&#8221; (that I interpret as &#8220;room for mistakes and laziness&#8221;).</p><p>You can go a little tidier when using type strict languages returning <code>0</code> or <code>-1</code> (thus needing a <code>signed int</code> return type).</p><p>Exceptions are handled in a different way (will explain further) and you won&#8217;t need anymore to chunk your funky error codes/messages into your return codes.</p><p><em>NOTE: All the examples are in <acronym
title="PHP: Hypertext Preprocessor">PHP</acronym> and functions are merely illustrative.</em></p><h2>Using <acronym
title="PHP: Hypertext Preprocessor">PHP</acronym>&#8217;s <code>trigger_error</code></h2><p>This function can help you to standardize your errors with <acronym
title="PHP: Hypertext Preprocessor">PHP</acronym>&#8217;s native errors like <strong>notices</strong> and <strong>fatal errors</strong>. I used this for long time attached to an <strong>error handler</strong> class. This worked out most for system errors and notices like &#8220;<em>unable to open file</em>&#8221; and such but they mostly were treated by issuing fatal errors and forcing user to a custom-built <strong>Error 500 &#8211; Internal Server Error</strong> page (in case of web code) or exiting to system with a custom error code.</p><h2>Testing with <code>if</code>/<code>else</code></h2><p>As mentioned above, I started handling errors with <strong>false-ing</strong> and <strong>null&#8217;ing</strong> the return of functions and checking them for that. Example:</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> find_id_by_name<span style="color: #009900;">&#40;</span><span style="color: #000088;">$name</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000088;">$query</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;SELECT id FROM users WHERE name = '<span style="color: #006699; font-weight: bold;">{$name}</span>'&quot;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000088;">$result</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$query</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">mysql_num_rows</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$result</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">else</span>
		<span style="color: #b1b100;">return</span> <span style="color: #990000;">mysql_result</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$result</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: function :: find_id_by_name</span></pre></div></div><p>And then checked when calling:</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$id</span> <span style="color: #339933;">=</span> find_id_by_name<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;John Doe&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span>
	<span style="color: #666666; font-style: italic;"># do stuff
</span><span style="color: #b1b100;">else</span><span style="color: #339933;">:</span>
	<span style="color: #666666; font-style: italic;"># print some message on screen
</span><span style="color: #b1b100;">endif</span><span style="color: #339933;">;</span></pre></div></div><p><em>NOTE: Returning zero (0) would trigger a false condition too.</em></p><p>Although this works pretty well it has several problems:</p><h3>Obtrusion</h3><p>If the checking code block prints messages on screen directly with <code>print</code> or <code>echo</code> it will be obtrusive for other functions calling it.</p><h3>Multiple fail points</h3><p>If a function can fail many ways, if you take the <code>false</code>/<code>null</code> approach you will know only that the function has failed but will have to insert debugging checkpoints on the function to know where it failed exactly.</p><p>Returning error codes may aid this point but cannot be used in <code>integer</code> functions because it would mix up with valid return entries and would still hurt our return type integrity.</p><h2>Return Codes</h2><p>As mentioned above, one could return integer error codes in order to identify the type of error that occurred. Although is a great leap in front of the <code>null</code>/<code>false</code> initiative.</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'ERROR_NO_USER'</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'ERROR_INVALID_PASSWORD'</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> auth_user<span style="color: #009900;">&#40;</span><span style="color: #000088;">$username</span><span style="color: #339933;">,</span> <span style="color: #000088;">$password</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> find_user<span style="color: #009900;">&#40;</span><span style="color: #000088;">$username</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000088;">$user</span><span style="color: #009900;">&#41;</span>
		<span style="color: #b1b100;">return</span> ERROR_NO_USER<span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$user</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">password</span> <span style="color: #339933;">!==</span> hash_function<span style="color: #009900;">&#40;</span><span style="color: #000088;">$password</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
		<span style="color: #b1b100;">return</span> ERROR_INVALID_PASSWORD
&nbsp;
	<span style="color: #b1b100;">return</span> <span style="color: #000088;">$user</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: function :: auth_user</span></pre></div></div><p>Note that this function returns an <code>Object</code> while it returns <code>integers</code> on failure.</p><p>To check if user has successfully authed, we would use something like:</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">is_numeric</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> auth_user<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;jdoe&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;passw0rd&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #666666; font-style: italic;"># hmmm... error occurred!
</span><span style="color: #b1b100;">else</span><span style="color: #339933;">:</span>
	<span style="color: #000088;">$_SESSION</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'user'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$user</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">endif</span><span style="color: #339933;">;</span></pre></div></div><p>But this still doesn&#8217;t seems right, and you still have to cluch a <code>switch</code> statement inside the error treating area to take actions depending on error code.</p><h3>Returning error codes in functions with integer return type</h3><p>In functions with integer return type you can&#8217;t return positive error codes because it would be confused with valid non-error entries unless you used negatively signed integers for that.</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> find_id_by_name<span style="color: #009900;">&#40;</span><span style="color: #000088;">$name</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;"># ... some code to get user data ...
</span>
	<span style="color: #666666; font-style: italic;"># User entry exists?
</span>	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000088;">$user</span><span style="color: #009900;">&#41;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;"># User account is inactive?
</span>	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$user</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">isInactive</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #cc66cc;">2</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> <span style="color: #000088;">$user</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">id</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: function :: find_id_by_name</span></pre></div></div><h2>Signaling failures in a return-safe manner</h2><p>You can always use a identifier of the same return type to illustrate failures. This technique can only be used to signalize entire function failure and does not gives you the fine grained error control that <code>try</code> gives.</p><h3>Integer return types</h3><p>Procedural languages like C has done this forever. In integer returned functions you can return <code>-1</code> to signalize function failure.</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> find_id_by_name<span style="color: #009900;">&#40;</span><span style="color: #000088;">$name</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;"># ... some code
</span>
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$ids</span><span style="color: #009900;">&#41;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #000088;">$id</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">else</span>
		<span style="color: #b1b100;">return</span> <span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: function :: find_id_by_name</span></pre></div></div><h3>Returning empty lists</h3><p>When dealing with function that returns lists (lists/arrays, dictionaries and such) you can also use an empty list in return signaling that no entries are found. This persists the function return-type and will flow naturally if parent function uses the returned value into a <code>foreach</code> or <code>for</code> statement.</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> find_users_by_country<span style="color: #009900;">&#40;</span><span style="color: #000088;">$country_id</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;"># ... some code
</span>
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$users</span><span style="color: #009900;">&#41;</span>
		<span style="color: #b1b100;">return</span> <span style="color: #000088;">$users</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">else</span>
		<span style="color: #b1b100;">return</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: function :: find_users_by_country</span></pre></div></div><h2>Using Try/Catch and Exceptions</h2><p>One of the greatest practices I learned in my life as a developer was to introduce the power of <code>try</code>/<code>catch</code> into my code. This long-known practice by Java users was introduced in <acronym
title="PHP: Hypertext Preprocessor">PHP</acronym> version 5 and I think it&#8217;s present in almost every OOP<a
title="OOP @ Wikipedia" href="http://en.wikipedia.org/wiki/Object_Oriented_Programming" class="wikipedia" rel="external wikipedia"><sup>w</sup></a> implementation like Java, PHP5, C++, Python and even in Flash AS3 (since its inherited from Java structure).</p><p>It gives you the ability to raise real-time errors during execution without the need to interfere within your returns. It helps you keeping your functions returning only data its expecting.</p><h3>Try/Catch overview</h3><p>The <code>try</code> block surrounds a set of statements that must &#8220;not throw an exception&#8221;  to proceed. If any of the inner statements <code>throw</code>s any exception, function execution proceeds but its routed to the <code>catch</code> block corresponding to the kind of exception that was raised.</p><p>But hell, what are exceptions?</p><p>As corrected by <a
href="http://blog.seanja.com/">SeanJA from SquirrelHacker</a> Exceptions are the Object-oriented form special errors that <strong>aren&#8217;t expected</strong> in the flow.</p><p>Exception are good to distinguish errors from each other from their class type. Exceptions can also have custom properties and methods for each type. You just have to define them in your exception class. They also extends a main Exception class with methods generally available to all classes such as the <code>getMessage</code> method in <acronym
title="PHP: Hypertext Preprocessor">PHP</acronym>.</p><p>In most implementation, exception classes often receives a custom message as first parameter that would be read later on by the corresponding <code>getMessage</code> method.</p><p>Example:</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;">try <span style="color: #009900;">&#123;</span>
	do_something<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	do_other_thing<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span> catch <span style="color: #009900;">&#40;</span>Exception <span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #b1b100;">print</span> <span style="color: #000088;">$e</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getMessage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: try</span></pre></div></div><h3>Throwing exceptions (errors)</h3><p>Inside your function you can use the <code>throw</code> statement to generate exceptions that will be caught in the <code>catch</code> block of the caller function. Lets rewrite our function used in the early example with exceptions.</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> find_id_by_name<span style="color: #009900;">&#40;</span><span style="color: #000088;">$name</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;"># ... some code to get user data ...
</span>
	<span style="color: #666666; font-style: italic;"># Connection is up?
</span>	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">conn</span><span style="color: #009900;">&#41;</span>
		<span style="color: #b1b100;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> Exception<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Connection was dropped.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">return</span> <span style="color: #000088;">$user</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">id</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: function :: find_id_by_name</span></pre></div></div><h3>Custom-built exceptions</h3><p>Working with generic exceptions is already very useful but it stills give you few control about the type of error generated. Generic exceptions are good if you will only catch and forward the error messages or if your error handling is independent of the error type.</p><p>You can easily generate custom exceptions by extending the main Exception class (varies according to the language). In <acronym
title="PHP: Hypertext Preprocessor">PHP</acronym>, this is the <code>Exception</code> class.</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> FileLockedException <span style="color: #000000; font-weight: bold;">extends</span> Exception <span style="color: #009900;">&#123;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: class :: FileLockedException</span></pre></div></div><p>That&#8217;s it, if you don&#8217;t need no additional methods or proprieties, you&#8217;re done! You may successful use your new exceptions while treating errors with <code>catch</code>. If you need it, just treat your Exception class as any normal OOP class.</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> FileLockedException <span style="color: #000000; font-weight: bold;">extends</span> Exception <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000088;">$timestamp</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: class :: FileLockedException</span>
&nbsp;
some_function<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000088;">$ex</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> FileLockedException<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$ex</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">timestamp</span> <span style="color: #339933;">=</span> <span style="color: #990000;">date</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Y-m-d H:i:s&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">throw</span> <span style="color: #000088;">$ex</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: function :: some_function</span></pre></div></div><h3>Catching exceptions</h3><p>As seen on the example on try/catch overview, catching just requires a <code>catch</code> statement for the corresponding Exception class. All exceptions that doesn&#8217;t have an <code>catch</code> statement for its own class type will fall back to the main exception class.</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;">try <span style="color: #009900;">&#123;</span>
&nbsp;
	do_something<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	do_other_thing<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span> catch <span style="color: #009900;">&#40;</span>FileLockedException <span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">print</span> <span style="color: #0000ff;">&quot;Cannot open file for writing, locked!&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span> catch <span style="color: #009900;">&#40;</span>Exception <span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #b1b100;">print</span> <span style="color: #000088;">$e</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getMessage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: try</span></pre></div></div><h3>Rethrow, bubbling up exceptions</h3><p>Exceptions can be bubbled up by rethrowing with a <code>throw</code> statement under a <code>catch</code> block. This is used to delegate the control of parsing the error to a parent function and to force triggering the <code>catch</code> blocks on them.</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> do_something<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	try <span style="color: #009900;">&#123;</span>
&nbsp;
		do_stuff<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009900;">&#125;</span> catch <span style="color: #009900;">&#40;</span>Exception <span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
		<span style="color: #b1b100;">throw</span> <span style="color: #000088;">$e</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: try</span>
&nbsp;
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: function :: do_something</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> do_stuff<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$somethingWentWrong</span><span style="color: #009900;">&#41;</span>
		<span style="color: #b1b100;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> Exception<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Something went wrong!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: function :: do_stuff</span></pre></div></div><h2>Overhead &#038; Overkill or When to use exceptions?</h2><p>SeanJA wrote <a
href="http://blog.seanja.com/2010/04/exceptions-are-not-for-flow-control/">an excellent article about that</a> clarifing some points (thanks SeanJA!).</p><p>To differ errors from exceptions, you need to point out if what you are returning is expected or not. You can achieve this by focusing on the purpose of your function.</p><p>To keep up with previous examples, lets assume our login function. Which is its purpose? The function is asked &#8220;This user credentials are valid?&#8221; and it expects &#8220;Yes&#8221; or &#8220;No&#8221;.</p><p>Credentials are a tuple of <strong>username</strong> and <strong>password</strong> so if one of these are wrong, your function should naturally return <code>false</code> because one of them are wrong, but that is expected.</p><p>Unexpected data is something that is beyond your control, like a locked file, a database timeout and such. Check out SeanJA if you need more clarification on this subject.</p><p>Once I got in love with Exceptions I can&#8217;t live without it. It gets you even more in depth within OOP, and I&#8217;m satisfied with it.</p><p>Treat your errors well and they will not betray you late in the nite!</p><p>No related posts.</p>]]></content:encoded> <wfw:commentRss>http://www.heavyworks.net/blog/posts/better-error-handling/feed</wfw:commentRss> <slash:comments>4</slash:comments> </item> <item><title>Smartly resolving your WordPress pages and posts JavaScript and CSS dependences</title><link>http://www.heavyworks.net/blog/posts/smartly-resolving-your-wordpress-pages-and-posts-javascript-and-css-dependences</link> <comments>http://www.heavyworks.net/blog/posts/smartly-resolving-your-wordpress-pages-and-posts-javascript-and-css-dependences#comments</comments> <pubDate>Tue, 23 Feb 2010 06:58:08 +0000</pubDate> <dc:creator>Jan Seidl</dc:creator> <category><![CDATA[Coding]]></category> <category><![CDATA[best practices]]></category> <category><![CDATA[custom fields]]></category> <category><![CDATA[get_post_meta]]></category> <category><![CDATA[wordpress]]></category> <category><![CDATA[wp_enqueue_script]]></category> <category><![CDATA[wp_enqueue_style]]></category> <guid
isPermaLink="false">http://www.heavyworks.net/?p=401</guid> <description><![CDATA[Sometimes you want to include page-specific or files and ended up in cluttered ifs and else ifs or even creating a creepy new page just for that. &#8216;s excellent plugin infrastructure with their hooks and actions provides us a beautiful and clean form of including our JavaScript in specific pages. In this tutorial, we will [...]
No related posts.]]></description> <content:encoded><![CDATA[<p>Sometimes you want to include page-specific JavaScript<a
title="JavaScript @ Wikipedia" href="http://en.wikipedia.org/wiki/Javascript" class="wikipedia" rel="external wikipedia"><sup>w</sup></a> or <acronym
title="Cascading Style Sheets">CSS</acronym><a
title="CSS @ Wikipedia" href="http://en.wikipedia.org/wiki/Css" class="wikipedia" rel="external wikipedia"><sup>w</sup></a> files and ended up in cluttered <code>if</code>s and <code>else if</code>s or even creating a creepy new page just for that.</p><p>Wordpress<a
title="Wordpress @ Wikipedia" href="http://en.wikipedia.org/wiki/Wordpress" class="wikipedia" rel="external wikipedia"><sup>w</sup></a>&#8216;s excellent plugin infrastructure with their hooks and actions provides us a beautiful and clean form of including our JavaScript in specific pages.</p><p>In this tutorial, we will be using three WordPress functions: <code>get_post_meta()</code> and <code>wp_enqueue_script()</code> and <code>wp_enqueue_style()</code>.<br
/> <span
id="more-401"></span></p><h2>Custom Fields</h2><p>Well, you may have noticed that <code>get_post_meta()</code> is about the custom fields and you&#8217;re just right.</p><p>We&#8217;ll be using posts and pages custom field to add scripts and stylesheet files. I&#8217;m using the keys &#8216;js&#8217; and &#8216;css&#8217; to JavaScript and <acronym
title="Cascading Style Sheets">CSS</acronym> files respectively.</p><p>If you don&#8217;t know how to use custom fields, please visit the <a
href="http://codex.wordpress.org/Custom_Fields">WordPress documentation on Custom Fields</a>.</p><p>The documentation on these functions are available at WordPress documentation site:</p><dl><dt><code>get_post_meta</code></dt><dd><a
href="http://codex.wordpress.org/Function_Reference/get_post_meta" title="get_post_meta documentation">http://codex.wordpress.org/Function_Reference/get_post_meta</a></dd><dt><code>wp_enqueue_style</code></dt><dd><a
href="http://codex.wordpress.org/Function_Reference/wp_enqueue_style" title="wp_enqueue_style documentation">http://codex.wordpress.org/Function_Reference/wp_enqueue_style</a></dd><dt><code>wp_enqueue_script</code></dt><dd><a
href="http://codex.wordpress.org/Function_Reference/wp_enqueue_script" title="wp_enqueue_script documentation">http://codex.wordpress.org/Function_Reference/wp_enqueue_script</a></dd></dl><h2><code>get_post_meta</code></h2><p>This function is responsible by getting our custom field entries and returning them as an array.<br
/> If one or more  entries are found, the array is returned with normal indexes (0..1&#8230;) and with the custom field values. If no entries are found, an empty array is returned.</p><p>Well, our return type will be always array so <code>foreach</code> will fit perfectly even on an empty set.</p><h2><code>header.php</code> file</h2><p>All code described in the following examples must be placed at least one line before the <code>wp_head()</code> function in your <code>header.php</code> file. if your <code>header.php</code> file is missing a <code>wp_head()</code> call, it shouldn&#8217;t. <code>wp_head()</code> function does lots of important things and many plugins use it. Please consider adding it to your code.</p><h2><code>wp_enqueue_script</code> and <code>wp_enqueue_style</code></h2><p>Some plugin developers may be not aware of these beautiful functions or even how scripts and stylesheets are managed by WordPress.</p><p>All scripts and style, when properly set, are enqueued and inserted automatically when <code>wp_head()</code> is called. Enqueuing your scripts and style are a better way other than just hooking <code>wp_head()</code> and printing to the output buffer.</p><p>This assures that our scripts and styles will be included only at the <code>wp_head()</code> call and will not be printed out from nowhere messing out peoples templates and plugins.</p><p><em>NOTE: Due the printing menace of <code>script</code> tags and JavaScript code chunks, <a
href="http://www.heavyworks.net/blog/tag/wp-minify"><acronym
title="WordPress">WP</acronym>-Minify</a> parses the ENTIRE site output in order to properly minify them.</em></p><p>This technique also prevents overlapping includes of twicely defined entries.</p><p><img
src="http://www.heavyworks.net/wordpress/wp-content/uploads/queue.gif" alt="CSS and JavaScript files happy in the queue" title="CSS and JavaScript files happy in the queue" width="600" height="417" class="aligncenter size-full wp-image-413" /><br
/> Wordpress gives us respectively <code>wp_enqueue_script</code> and <code>wp_enqueue_style</code> for enqueueing scripts and stylesheets. Both functions receive a script or stylesheet unique identifier as the first parameter and the path as second (more parameters are available, please refer to the documentation for more understanding on this subject).</p><p>As this is an automated process, I&#8217;m using as unique identifier the md5 hash of the file&#8217;s path (the custom field value).</p><p><em>NOTE: This solution is made for JavaScript and <acronym
title="Cascading Style Sheets">CSS</acronym> files that follows a unique parent directory. Please refer to the examples for more explanation.</em></p><p>So let&#8217;s get back to our <code>header.php</code> file just before the <code>wp_head()</code> call that we mentioned before. We also remember that the custom field key for JavaScript files that we&#8217;ll be using in this example is &#8216;js&#8217;.</p><h3>JavaScript files</h3><p>The following code will use <code>get_post_meta</code> to get the array (empty or not) of JavaScript files that have been set through custom fields under the <code>js</code> folder under our template directory.</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$js</span> <span style="color: #339933;">=</span> get_post_meta<span style="color: #009900;">&#40;</span><span style="color: #000088;">$post</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">ID</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'js'</span><span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$jscript</span><span style="color: #009900;">&#41;</span> wp_enqueue_script<span style="color: #009900;">&#40;</span><span style="color: #990000;">md5</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$jscript</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>get_bloginfo<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'template_directory'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">'/js/'</span><span style="color: #339933;">.</span><span style="color: #000088;">$jscript</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div><h3><acronym
title="Cascading Style Sheets">CSS</acronym> files</h3><p>The following code will use <code>get_post_meta</code> to get the array (empty or not) of <acronym
title="Cascading Style Sheets">CSS</acronym> files that have been set through custom fields under the <code>css</code> folder under our template directory.</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$css</span> <span style="color: #339933;">=</span> get_post_meta<span style="color: #009900;">&#40;</span><span style="color: #000088;">$post</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">ID</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'css'</span><span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$style</span><span style="color: #009900;">&#41;</span> wp_enqueue_style<span style="color: #009900;">&#40;</span><span style="color: #990000;">md5</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$style</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>get_bloginfo<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'template_directory'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">'/css/'</span><span style="color: #339933;">.</span><span style="color: #000088;">$style</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div><p>Simple huh? One line each and your problems are solved.</p><p>You may now call <code>wp_head()</code> and go drink your coffee!</p><p>No related posts.</p>]]></content:encoded> <wfw:commentRss>http://www.heavyworks.net/blog/posts/smartly-resolving-your-wordpress-pages-and-posts-javascript-and-css-dependences/feed</wfw:commentRss> <slash:comments>5</slash:comments> </item> <item><title>5 best practices on developing WordPress plugins</title><link>http://www.heavyworks.net/blog/posts/5-best-practices-on-developing-wordpress-plugins</link> <comments>http://www.heavyworks.net/blog/posts/5-best-practices-on-developing-wordpress-plugins#comments</comments> <pubDate>Sun, 21 Feb 2010 19:34:20 +0000</pubDate> <dc:creator>Jan Seidl</dc:creator> <category><![CDATA[Coding]]></category> <category><![CDATA[best practices]]></category> <category><![CDATA[cleanup]]></category> <category><![CDATA[debug]]></category> <category><![CDATA[i18n]]></category> <category><![CDATA[internationalization]]></category> <category><![CDATA[plugins]]></category> <category><![CDATA[wordpress]]></category> <guid
isPermaLink="false">http://www.heavyworks.net/?p=383</guid> <description><![CDATA[Wordpress wonders me how it born as a Blogging platform and is growing a powerful CMS platform. Its plugin framework is full of hooks and actions and almost everything can be trapped and modified by plugins. As WordPress is a oriented platform the function wrapped to the hooks and actions have no scope when called [...]
No related posts.]]></description> <content:encoded><![CDATA[<p><img
src="http://www.heavyworks.net/wordpress/wp-content/uploads/plugin.jpg" alt="Wordpress Plugins" title="Wordpress Plugins" width="484" height="296" class="aligncenter size-full wp-image-395" /><br
/> Wordpress wonders me how it born as a Blogging platform and is growing a powerful <acronym
title="Content Management System">CMS</acronym> platform. Its plugin framework is full of hooks and actions and almost everything can be trapped and modified by plugins.</p><p>As WordPress is a Procedural Programming<a
title="Procedural Programming @ Wikipedia" href="http://en.wikipedia.org/wiki/Procedural_programming" class="wikipedia" rel="external wikipedia"><sup>w</sup></a> oriented platform the function wrapped to the hooks and actions have no scope when called except global this can be hell when developing plugins. We must take extra-care to not compromise our plugin security and compatibility.</p><p>In our road developing plugins we learned some lessons, here is our share.<span
id="more-383"></span></p><h2>1. Enable your WP_DEBUG</h2><p>This caused me some nightmares the first time I turned it on. Lots of plugin developers doesn&#8217;t have the habit of working with <acronym
title="PHP: Hypertext Preprocessor">PHP</acronym>&#8217;s <code>error_reporting</code> at the <code>E_ALL</code> level (Maximum Level, including notices of undefined variables) and I god SEVERAL notices on screen.</p><p><code>WP_DEBUG</code> can be enabled by simply adding the following line to your <code>wp-config.php</code> file.</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'WP_DEBUG'</span><span style="color: #339933;">,</span><span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div><p><acronym
title="PHP: Hypertext Preprocessor">PHP</acronym> is a very friendly (if we can call this way) programming language that doesn&#8217;t cares very much to variable initialization but you should initialize all your variables and check if they are set with the language&#8217;s native <code>isset()</code> function.</p><p>If you have <code>WP_DEBUG</code> you will se NO errors at all so if your script breaks somewhere at the development, you&#8217;ll suffer lots of pain trying to blindly debug your code. Lots of experience had me finding unclosed brackets, parentheses and semicolons but, come on, I&#8217;m no masochist.</p><p>The best tip here is to have a development WordPress installation. If this is not possible (or you are just too lazy), as lots of plugin developers (very popular ones) aren&#8217;t caring about notices showing up to your visitors if you have WP_DEBUG enabled you can always use the good and old <acronym
title="PHP: Hypertext Preprocessor">PHP</acronym> code to enable debug only if you are the visitor.</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;"># 200.200.200.200 is an example IP and should be replaced by your own
</span><span style="color: #666666; font-style: italic;"># if you don't know your IP you can visit www.whatismyip.com
</span><span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$_SERVER</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'REMOTE_ADDR'</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">'200.200.200.200'</span><span style="color: #009900;">&#41;</span> <span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'WP_DEBUG'</span><span style="color: #339933;">,</span><span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div><h2>2. Have a cleanup deactivation routine</h2><p>Had you ever took a look at your <code>wp_options</code> table after a long time activating and deactivating plugins? If you so you probably had seen the garbage left out there.</p><p>If you are going to write an option with <cod>add_option</code> or <code>update_option</code> please, please, please, be sure to remove your options upon plugin deactivation. I'm pretty sure no one wants your options leftovers as a souvenir.</p><p>To achieve such thing, you must register a deactivation hook by the <code>register_deactivation_hook</code> as following</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;">register_deactivation_hook<span style="color: #009900;">&#40;</span> <span style="color: #009900; font-weight: bold;">__FILE__</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'plugin_deactivate'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div><p>And obviously you will have to code an appropriate deactivation function, like <code>plugin_deactivate</code> in the example.</p><p><em>NOTE: Your deactivation function must be at the script's main <acronym
title="PHP: Hypertext Preprocessor">PHP</acronym> file.</em><br
/> <em>NOTE: Your deactivation function may have any name.</em><br
/> <em>NOTE: The <code>__FILE__</code> part specified at the deactivation hook is referencing your own script file.</em></p><p>I personally put all my options that goes to the <code>wp_options</code> database in a global associative array so if I add more options my cleanup function will still be compliant.</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">global</span> <span style="color: #000088;">$aOptions</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$aOptions</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
    <span style="color: #0000ff;">'myplugin-default-lang'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'en_US'</span>
<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div><p>I also put my deactivation and cleanup functions apart so I can call the cleanup from within the deactivation function. This is made so if I want to add more deactivation functionalities else than cleanup I can do this without polluting my cleanup function with non-cleanup procedures.</p><p>The <code>plugin_deactivate</code> function will look like the following:</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> plugin_deactivate<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// Cleanup</span>
    plugin_cleanup<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: function :: plugin_deactivate</span></pre></div></div><p>And the cleanup function as it follows:</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> plugin_cleanup<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">global</span> <span style="color: #000088;">$aOptions</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Delete our options</span>
    <span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$aOptions</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$sOptionKey</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000088;">$sOptionValue</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span>
        delete_option<span style="color: #009900;">&#40;</span><span style="color: #000088;">$sOptionKey</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">endforeach</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: function :: plugin_cleanup</span></pre></div></div><p>This should be enough to keep your options table tidy.</p><h2>3. Protect files that shouldn't be accessed directly</h2><p>Almost all your plugin files shouldn't be access directly. Exception goes to scripts that receives data from outside the WordPress framework like thumbnail generators, image replacement techniques, <acronym
title="Asynchronous JavaScript and XML">AJAX</acronym>, and such.</p><p>To disable direct access to your <acronym
title="PHP: Hypertext Preprocessor">PHP</acronym> files you must check if some WordPress function is present and if not, shutdown the script if a good and old <code>exit();</code> call.</p><p>The example goes as:</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #990000;">function_exists</span> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'add_action'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span>
    <span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Status: 403 Forbidden'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'HTTP/1.1 403 Forbidden'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #990000;">exit</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">endif</span><span style="color: #339933;">;</span></pre></div></div><p>The example above also sends a 403 header in both formats (Internet Explorer and decent browsers, respectively).</p><h2>4. Use internationalization even if you aren't going to translate yet</h2><p>Even if you are not planning release you plugin with many languages I strongly recommend that you build yours i18n-ready by wrapping your texts on <code>gettext<a
title="gettext @ Wikipedia" href="http://en.wikipedia.org/wiki/Gettext" class="wikipedia" rel="external wikipedia"><sup>w</sup></a></code> functions so other users can help (or even you in the future) to translate your plugin.</p><h3>The basics</h3><p>Internationalization basics in <acronym
title="PHP: Hypertext Preprocessor">PHP</acronym> is very simple. There are mainly two functions: <code>__()</code> and <code>_e()</code>. The difference is that <code>__()</code> returns the internationalized string <code>_e()</code> <code>echo</code>es it.</p><p>When text is within a variable or returned by a function you should use the <code>__()</code> function and if you want to <code>echo</code> it, <code>_e()</code> instead.</p><h4>Echoing internationalized text in a template file</h4><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;">&lt;h2&gt;<span style="color: #000000; font-weight: bold;">&lt;?php</span> _e<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'My text goes here'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'My text domain goes here'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&lt;/h2&gt;</pre></div></div><h4>Returning internationalized text in a function</h4><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> somefunction<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">return</span> __<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'My text goes here'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'My text domain goes here'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;&lt;/</span>h2<span style="color: #339933;">&gt;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: function :: somefunction</span></pre></div></div><p>Internationalization is a wide subject and is covered greatly in the WordPress "<a
href="http://codex.wordpress.org/Writing_a_Plugin#Internationalizing_Your_Plugin">Writing a Plugin</a>" page.</p><p>Internationalizing your plugin is also a good marketing strategy since if someone releases a language file for your plugin, is also making it available in a wider market-share slice.</p><h2>5. Employ current coding best practices</h2><p>There are some wide best practices that are not exclusively to the WordPress Plugin scope.</p><h3>Separate your code</h3><p>Applying this technique on WordPress Plugin development is such as having the plugin's main php file just making the calls and registering the hooks and have your functions properly laid under a <code>lib/</code> function or such. Same things goes to <code>images/</code>, <code>js/</code> (JavaScript) and <code>css/</code>.</p><h3>Document your code</h3><p>Ok, this is like telling grown-ups to not touch the hot oven or putting the finger in a wall socket but many people still lacks in documenting code.</p><p>I suggest to keep your functions, classes and files documented in the <a
href="http://www.phpdoc.org/">phpDocumentor</a> syntax.</p><p>This kind of syntax is inherited from Java and other languages apply it since is very readable and parse-able.</p><p>It goes like the following:</p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #009933; font-style: italic;">/**
 * My loved function
 *
 * This function collects some data and process in this way to give the desired result.
 *
 * @param    string   $varname    Description of the variable
 * @param    int   $othervarname    Description of the variable
 * @return    void   This function returns nothing
 */</span></pre></div></div><h3>Stay DRY</h3><p>Try to avoid two functions that do basically the same thing. If you have two functions in separate classes that to the same thing (like string sanitization), consider having a utility class.</p><h2>Bonus Tip!</h2><p> Avoid kidnapping people's <code>wp_head()</code> and <code>wp_footer()</code> with your plugin propaganda. If you want to make such thing, do as <acronym
title="HyperText Markup Language">HTML</acronym> code comment or make this branding stuff optional.</p><p>If you are going to make your plugin free, make it free, not AD dependant. If you think your plugin should be paid, then make it paid. Placing plugin ADs in the themplate may scare out some users. Your free plugin shall make your own propaganda by being useful and rich-featured, not by printing it out.</p><p>What's your tip?</p><p>No related posts.</p>]]></content:encoded> <wfw:commentRss>http://www.heavyworks.net/blog/posts/5-best-practices-on-developing-wordpress-plugins/feed</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Alternative syntax for PHP control structures</title><link>http://www.heavyworks.net/blog/posts/alternative-syntax-for-php-control-structures</link> <comments>http://www.heavyworks.net/blog/posts/alternative-syntax-for-php-control-structures#comments</comments> <pubDate>Sat, 02 Jan 2010 21:46:40 +0000</pubDate> <dc:creator>Jan Seidl</dc:creator> <category><![CDATA[Coding]]></category> <category><![CDATA[alternative]]></category> <category><![CDATA[php]]></category> <category><![CDATA[syntax]]></category> <guid
isPermaLink="false">http://www.heavyworks.net/?p=314</guid> <description><![CDATA[While it&#8217;s not a great secret, many people still not aware of the alternative syntax for control structures under PHP. The C-like syntax for control structures are very intuitive but can deal lots of trouble when your code has lot of pages and lots of ifs, fors, while and therefore lots of opening and closing [...]
No related posts.]]></description> <content:encoded><![CDATA[<p>While it&#8217;s not a great secret, many people still not aware of the alternative syntax for control structures under <acronym
title="PHP: Hypertext Preprocessor">PHP</acronym>.</p><p>The C-like syntax for control structures are very intuitive but can deal lots of trouble when your code has lot of pages and lots of <code>if</code>s, <code>for</code>s, <code>while</code> and therefore lots of opening and closing braces.</p><p><em>NOTE: As <a
title="Alternative syntax for PHP control structures by Heavyworks @ DZone" href="http://www.dzone.com/links/alternative_syntax_for_php_control_structures.html#111906199">remembered by jakyra on DZone</a>, if you keep your code tidy you shouldn&#8217;t have functions that long and though not having this kind of problem, but this alternative syntax still have good benefits.</em></p><p><img
src="http://www.heavyworks.net/wordpress/wp-content/uploads/braces.jpg" alt="" title="No more losing in between braces" width="500" height="215" class="aligncenter size-full wp-image-328" /></p><h2>The alternative syntax</h2><p>The alternative syntax consists in changing the opening brace (<code>{</code>) to a colon (<code>:</code>) and each closing brace to its respective closing function: <code>endif;</code>, <code>endfor;</code>, <code>endforeach;</code>, <code>endwhile;</code> and <code>endswitch;</code>.<br
/> <span
id="more-314"></span></p><h2>Closing functions list</h2><dl><dt>opens <code>if ([parameters]):</code></dt><dd>closes <code>endif;</code></dd><dt>opens <code>for ([parameters]):</code></dt><dd>closes <code>endfor;</code></dd><dt>opens <code>foreach ([parameters]):</code></dt><dd>closes <code>endforeach;</code></dd><dt>opens <code>while ([parameters]):</code></dt><dd>closes <code>endwhile;</code></dd><dt>opens <code>switch ([value]):</code></dt><dd>closes <code>endswitch;</code></dd></dl><h2>Benefits of this alternative syntax</h2><p>The benefits of using this syntax are clear when put into practice. A far more readable code with no more commenting out braces like <code>} // end :: if</code>. You can instantly know which structural condition this closing brace belongs to and will no longer get confused between these and function braces.</p><h2>Disadvantages of the alternative syntax</h2><p>I personally do not consider this as a disadvantage but some people might consider since some text editors and IDEs have the ability to highlight the matching brace.</p><h2>Examples</h2><h3>If</h3><p><em>NOTE: <code>else</code> and <code>elseif</code> control structures follow the same structure.</em></p><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Standard syntax</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$variable</span> <span style="color: #339933;">===</span> <span style="color: #009900; font-weight: bold;">TRUE</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$otherVariable</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;foo&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$aThirdVariable</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;bar&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">elseif</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$variable</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">&quot;foo&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$otherVariable</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;foo&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$aThirdVariable</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;foo&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$otherVariable</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;bar&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$aThirdVariable</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;foo&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: if</span></pre></div></div><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Alternative syntax</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$variable</span> <span style="color: #339933;">===</span> <span style="color: #009900; font-weight: bold;">TRUE</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span>
	<span style="color: #000088;">$otherVariable</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;foo&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$aThirdVariable</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;bar&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">elseif</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$variable</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">&quot;foo&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span>
	<span style="color: #000088;">$otherVariable</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;foo&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$aThirdVariable</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;foo&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">else</span><span style="color: #339933;">:</span>
	<span style="color: #000088;">$otherVariable</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;bar&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$aThirdVariable</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;foo&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">endif</span><span style="color: #339933;">;</span></pre></div></div><h3>Foreach</h3><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$array</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;foo&quot;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;bar&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Standard syntax</span>
<span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$array</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$key</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$foo</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$key</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$bar</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$value</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: foreach</span></pre></div></div><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$array</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;foo&quot;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;bar&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Alternative syntax</span>
<span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$array</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$key</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span>
	<span style="color: #000088;">$foo</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$key</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$bar</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$value</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">endforeach</span><span style="color: #339933;">;</span></pre></div></div><h3>For</h3><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Standard syntax</span>
<span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>
	<span style="color: #000088;">$i</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$i</span><span style="color: #339933;">&lt;</span><span style="color: #cc66cc;">10</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$i</span><span style="color: #339933;">++</span>
<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$foo</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$i</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$bar</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$i</span><span style="color: #339933;">*</span><span style="color: #cc66cc;">10</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">print</span> <span style="color: #000088;">$foo</span><span style="color: #339933;">+</span><span style="color: #000088;">$bar</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: for</span></pre></div></div><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Alternative syntax</span>
<span style="color: #b1b100;">for</span> <span style="color: #009900;">&#40;</span>
	<span style="color: #000088;">$i</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$i</span><span style="color: #339933;">&lt;</span><span style="color: #cc66cc;">10</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$i</span><span style="color: #339933;">++</span>
<span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span>
	<span style="color: #000088;">$foo</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$i</span><span style="color: #339933;">;</span>
	<span style="color: #000088;">$bar</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$i</span><span style="color: #339933;">*</span><span style="color: #cc66cc;">10</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">print</span> <span style="color: #000088;">$foo</span><span style="color: #339933;">+</span><span style="color: #000088;">$bar</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">endfor</span><span style="color: #339933;">;</span></pre></div></div><h3>While</h3><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$i</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">10</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Standard syntax</span>
<span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$i</span> <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000088;">$foo</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$i</span><span style="color: #339933;">--;</span>
	<span style="color: #b1b100;">print</span> <span style="color: #000088;">$foo</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: while</span></pre></div></div><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$i</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">10</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Alternative syntax</span>
<span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$i</span> <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span>
	<span style="color: #000088;">$foo</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$i</span><span style="color: #339933;">--;</span>
	<span style="color: #b1b100;">print</span> <span style="color: #000088;">$foo</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">endwhile</span><span style="color: #339933;">;</span></pre></div></div><h3>Switch</h3><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Standard syntax</span>
<span style="color: #b1b100;">switch</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$foo</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
<span style="color: #b1b100;">case</span> <span style="color: #0000ff;">&quot;foo&quot;</span><span style="color: #339933;">:</span>
	<span style="color: #000088;">$bar</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">FALSE</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">case</span> <span style="color: #0000ff;">&quot;bar&quot;</span><span style="color: #339933;">:</span>
<span style="color: #b1b100;">default</span><span style="color: #339933;">:</span>
	<span style="color: #000088;">$bar</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">TRUE</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// end :: switch</span></pre></div></div><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Alternative syntax</span>
<span style="color: #b1b100;">switch</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$foo</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span>
<span style="color: #b1b100;">case</span> <span style="color: #0000ff;">&quot;foo&quot;</span><span style="color: #339933;">:</span>
	<span style="color: #000088;">$bar</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">FALSE</span><span style="color: #339933;">;</span>
	<span style="color: #b1b100;">break</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">case</span> <span style="color: #0000ff;">&quot;bar&quot;</span><span style="color: #339933;">:</span>
<span style="color: #b1b100;">default</span><span style="color: #339933;">:</span>
	<span style="color: #000088;">$bar</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">TRUE</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">endswitch</span><span style="color: #339933;">;</span></pre></div></div><p><em>Photo: <a
href="http://www.flickr.com/photos/andyfitz/3658091463/">Andy Fitz @ Flickr</a></em></p><p>No related posts.</p>]]></content:encoded> <wfw:commentRss>http://www.heavyworks.net/blog/posts/alternative-syntax-for-php-control-structures/feed</wfw:commentRss> <slash:comments>9</slash:comments> </item> <item><title>Sustainability application under Software Development</title><link>http://www.heavyworks.net/blog/posts/sustainability-application-under-software-development</link> <comments>http://www.heavyworks.net/blog/posts/sustainability-application-under-software-development#comments</comments> <pubDate>Tue, 08 Dec 2009 21:42:16 +0000</pubDate> <dc:creator>Jan Seidl</dc:creator> <category><![CDATA[Coding]]></category> <category><![CDATA[caching]]></category> <category><![CDATA[carbon footprint]]></category> <category><![CDATA[compression]]></category> <category><![CDATA[global warming]]></category> <category><![CDATA[green]]></category> <category><![CDATA[optimization]]></category> <category><![CDATA[performance]]></category> <guid
isPermaLink="false">http://www.heavyworks.net/?p=287</guid> <description><![CDATA[We are constantly trying to improve our web applications performance to gain speed, lower the load on the clusters and thus being able to attend to even more users but have you ever thought about how these improvements can aid Global Warming? For years optimization techniques such as Caching in many levels (Disk/Memory), Compression, Clustering [...]
No related posts.]]></description> <content:encoded><![CDATA[<p>We are constantly trying to improve our web applications performance to gain speed, lower the load on the clusters and thus being able to attend to even more users but have you ever thought about how these improvements can aid <a
href="http://en.wikipedia.org/wiki/Global_Warming">Global Warming</a>?</p><p>For years optimization techniques such as <a
href="http://en.wikipedia.org/wiki/Caching">Caching</a> in many levels (Disk/Memory), <a
href="http://en.wikipedia.org/wiki/HTTP_compression">Compression</a>, <a
href="http://en.wikipedia.org/wiki/Cluster_(computing)">Clustering</a> and other were developed to acheive greater performance.</p><p>Global Warming is there for years and is getting worse every year but it seems that movements under IT has begun in order to create greener solutions. Many hosts such as <a
href="http://www.dreamhost.com/aboutus-green.html">Dreamhost</a> (which we&#8217;re proud of being our hosting company) have already started their effort in reducing or even neutralizing their <a
href="http://en.wikipedia.org/wiki/Carbon_Footprint">Carbon Footprint</a> and now developers can help on their side too.<br
/> <span
id="more-287"></span></p><h2>The Concept</h2><p><img
src="http://www.heavyworks.net/wordpress/wp-content/uploads/lamp-300x201.jpg" alt="Green Energy" title="Green Energy" width="300" height="201" class="alignright size-medium wp-image-298" /> Well, we don&#8217;t have to go too far to realize where optimization crosses paths with sustainability. It&#8217;s simple, it&#8217;s all about electricity (power) saving.</p><p>Again, it&#8217;s all about electricity. Every single bit minor instruction spends a very little piece of energy that goes through the processor and memory I/O operations and spends some little more sending data over the ethernet ports.</p><p>Let&#8217;s go from the beginning. The user has requested a website, the request goes through all the routers and switches in the way to the requisition.</p><p><em>NOTE: We are not considering this power consumption because it is not dependent on the application&#8217;s optimization.</em></p><p>Here is where optimization makes the difference: the way back.</p><p>Larger image or source files will take more CPU cycles to be processed, more Disk usage and more space allocated in memory. Then these big files have to be sent to the client and if you have many files this means more <acronym
title="HyperText Transfer Protocol">HTTP</acronym> connections and headers being sent.</p><p>Techniques such <a
href="http://www.alistapart.com/articles/sprites/"><acronym
title="Cascading Style Sheets">CSS</acronym> Sprites</a> (heavily used by <a
href="http://www.google.com">Google</a> and other big companies) aid to reduce the <acronym
title="HyperText Transfer Protocol">HTTP</acronym> Connections between the server and the client.</p><p>Each <acronym
title="HyperText Transfer Protocol">HTTP</acronym> connections contains not only the file&#8217;s data but it is preceded by header data with the file&#8217;s type, modified date and some other info so two square 20px images are bigger than one rectangular 40px per 20px image (the two 20px square images side by side).</p><p><img
src="http://www.heavyworks.net/wordpress/wp-content/uploads/routing_engine.jpg" alt="Routing" title="Routing" width="511" height="348" class="aligncenter size-full wp-image-295" /><br
/> Then the requested files come from the server to the client by all the router and switches in-between them spending more power in transmission until it gets to its destiny where will consume more power to be rendered by client browser&#8217;s engine and window manager (Windows, Gnome, Kde etc).</p><h2>How to collaborate?</h2><p>Optimize your software. <a
href="http://www.yahoo.com">Yahoo</a>&#8216;s <a
href="http://developer.yahoo.com/yslow/">YSlow</a> and <a
href="http://www.google.com">Google</a>&#8216;s <a
href="http://code.google.com/speed/page-speed/">Page Speed</a> are great kickstarts. You can also check <a
href="http://www.heavyworks.net/blog/tag/caching">our articles on caching</a>.</p><p>As all great saving and recycling, results will only take place with everyone&#8217;s effort. These taken under huge proportions can result in great saving and thus more breathe to our planet.</p><p>Think green.</p><h2>Other considerations under power saving on software development</h2><p>In this <a
title="Black Google would save 3000 megawatts @ EcoIron" href="http://ecoiron.blogspot.com/2007/08/history-in-january-2007-mark-ontkush.html">2007 article</a>, Mark Ontkush showed his study where dark-pallete-themed web applications required less energy from users&#8217; CRT monitors.</p><blockquote><p>&#8220;an all white web page uses about 74 watts to display, while an all black page uses only 59 watts. I thought I would do a little math and see what could be saved by moving a high volume site to the black format.&#8221;</p></blockquote><p><em>Mark Ontkush</em></p><p>And then the results came when he compared to traffic reports of huge websites such as Google:</p><blockquote><p>Take at look at Google, who gets about 200 million queries a day. Let&#8217;s assume each query is displayed for about 10 seconds; that means Google is running for about 550,000 hours every day on some desktop. Assuming that users run Google in full screen mode, the shift to a black background [on a CRT monitor! mjo] will save a total of 15 (74-59) watts. That turns into a global savings of 8.3 Megawatt-hours per day, or about 3000 Megawatt-hours a year. Now take into account that about 25 percent of the monitors in the world are CRTs, and at 10 cents a kilowatt-hour, that&#8217;s $75,000, a goodly amount of energy and dollars for changing a few color codes.</p></blockquote><p><em>Mark Ontkush</em></p><p>Black is the new black!</p><p>Unfortunately, dark-themed websites tend to be less accepted by the users, and some have even reported that white characters tend to blur by reading stress while reading an extensive text.</p><p>And you developer? What are you doing to save the world?</p><p>No related posts.</p>]]></content:encoded> <wfw:commentRss>http://www.heavyworks.net/blog/posts/sustainability-application-under-software-development/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Writing less: Using scientific notation for very large or very small numbers</title><link>http://www.heavyworks.net/blog/posts/writing-less-using-scientific-notation-for-very-large-or-very-small-numbers</link> <comments>http://www.heavyworks.net/blog/posts/writing-less-using-scientific-notation-for-very-large-or-very-small-numbers#comments</comments> <pubDate>Tue, 30 Jun 2009 01:29:19 +0000</pubDate> <dc:creator>Jan Seidl</dc:creator> <category><![CDATA[Coding]]></category> <category><![CDATA[math]]></category> <category><![CDATA[scientifc notation]]></category> <category><![CDATA[writing less]]></category> <guid
isPermaLink="false">http://www.heavyworks.net/?p=232</guid> <description><![CDATA[When dealing with very large or very small numbers we can opt by writing them under scientific notation. Scientific notation, also known as standard form or as exponential notation, is a way of writing numbers that accommodates values too large or small to be conveniently written in standard decimal notation. Scientific notation has a number [...]
No related posts.]]></description> <content:encoded><![CDATA[<p>When dealing with very large or very small numbers we can opt by writing them under scientific notation.</p><blockquote><p>Scientific notation, also known as standard form or as exponential notation, is a way of writing numbers that accommodates values too large or small to be conveniently written in standard decimal notation. Scientific notation has a number of useful properties and is often favored by scientists, mathematicians and engineers, who work with such numbers.</p></blockquote><p><em><a
href="http://en.wikipedia.org/wiki/Scientific_notation">Scientific Notation @ Wikipedia</a></em></p><p>So as we &#8211; developers &#8211; are part-scientists,part-mathematicians and part-engineers, so I guess this is perfect for us!</p><p>We have all seen that on high school and it seemed quite strange but it is quite simple indeed:</p><h2>Equation</h2><p>The equation is as it follows in a simplified language:<br
/> <code>Simplified number x10<sup>number of decimal units</sup></code></p><p>The &#8220;Simplified number&#8221; is the number in a simplified manner.<br
/> Examples:</p><ul><li>1000000 = 1</li><li>4230000 = 423</li></ul><p>And then we just add in the other hand the number of decimal units that were simpled-out.</p><ul><li>1000000 becomes 1&#215;10<sup>6</sup></li><li>4230000 becomes 423&#215;10<sup>4</sup></li></ul><p><span
id="more-232"></span><br
/> You can even balance decimal units as you want as <code>423x10<sup>4</sup></code> can also be written as <code>4.23x10<sup>6</sup></code>. Add to the decimal units the number of units before your period &#8220;.&#8221;. The goal is to keep the number as lowest (simple) possible so generally the <code>4.23x10<sup>6</sup></code> approach is preferred.</p><h2>Negative / Very small numbers</h2><p>Scientific notation can also represent the low numbers by negativing the decimal units count on the equation:<br
/> <code>4.23x10<sup>-4</sup> becomes 0.000423</code></p><p>Note that we have 6 units on the decimal side (4 from the <sup>-4</sup> and other two from the two decimal units at the multiplying part). That easy.</p><h2>Caution!</h2><p>This can be used to simplify virtually any number but I assume you won&#8217;t start writing 4&#215;10<sup>2</sup> instead of 400! Scientific notation is good to simplify great numbers but may also lead to a less-readable code. It is a good practice to assign these values to constants or comment-out.</p><h2>Language implementation</h2><p>Each language defines its own way to handle scientific notation here are some examples:</p><dl><dt>C++</dt><dd><div
class="wp_syntax"><div
class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">const</span> <span style="color: #0000ff;">float</span> FIVEMILLION <span style="color: #000080;">=</span> <span style="color:#800080;">5e6</span><span style="color: #008080;">;</span>
<span style="color: #0000ff;">const</span> <span style="color: #0000ff;">float</span> FIVECENTS <span style="color: #000080;">=</span> <span style="color:#800080;">5e-2</span><span style="color: #008080;">;</span></pre></div></div></dd><dt><acronym
title="PHP: Hypertext Preprocessor">PHP</acronym></dt><dd><div
class="wp_syntax"><div
class="code"><pre class="php" style="font-family:monospace;"><span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'FIVEMILLION'</span><span style="color: #339933;">,</span><span style="color:#800080;">5e6</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'FIVECENTS'</span><span style="color: #339933;">,</span><span style="color:#800080;">5e-2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div></dd></dl><p><em>NOTE: There are implementation in other languages than listed above</em></p><p><em>NOTE: Scientific Notation is also present in several applications (even the simplest desk calculator) when the output number is too large represented by the <code>E</code> letter followed by the <code>power</code> that is elevated.</em></p><p>Which is your idea for writing less code?</p><p>No related posts.</p>]]></content:encoded> <wfw:commentRss>http://www.heavyworks.net/blog/posts/writing-less-using-scientific-notation-for-very-large-or-very-small-numbers/feed</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>WP-Minify&#8217;s new version vanished WordPress&#8217; HTTP requests issue</title><link>http://www.heavyworks.net/blog/posts/wp-minifys-new-version-vanished-wordpress-http-requests-issue</link> <comments>http://www.heavyworks.net/blog/posts/wp-minifys-new-version-vanished-wordpress-http-requests-issue#comments</comments> <pubDate>Tue, 23 Jun 2009 00:01:08 +0000</pubDate> <dc:creator>Jan Seidl</dc:creator> <category><![CDATA[Coding]]></category> <category><![CDATA[google code]]></category> <category><![CDATA[minify]]></category> <category><![CDATA[php]]></category> <category><![CDATA[wordpress]]></category> <category><![CDATA[wp-minify]]></category> <guid
isPermaLink="false">http://www.heavyworks.net/?p=229</guid> <description><![CDATA[While working with WordPress we always stuck with the HTTP requests issue caused by plugins that appends external JavaScript or CSS files to our page body thus causing more http requests and downgrading our performance benchmark tests and company job standards. Content minification is a well-known best-practice for bandwidth reduction (saves client&#8217;s money) thus giving [...]
No related posts.]]></description> <content:encoded><![CDATA[<p>While working with WordPress we always stuck with the <acronym
title="HyperText Transfer Protocol">HTTP</acronym> requests issue caused by plugins that appends external JavaScript or <acronym
title="Cascading Style Sheets">CSS</acronym> files to our page body thus causing more http requests and downgrading our performance benchmark tests and company job standards.</p><p><a
href="http://en.wikipedia.org/wiki/Minify" title="Minify @ Wikipedia">Content minification</a> is a well-known best-practice for bandwidth reduction (saves client&#8217;s money) thus giving better page load time (gives client a good smile). Since it removes all unnecessary code (like comments, extra spaces, tabs etc) and join files together, the total of KBs saved even in bandwidth and browser rendering.</p><p>Here we always implemented the <a
href="http://code.google.com/p/minify/">Minify PHP5 tool from Steve Clay and Ryan Grove</a> because it always worked like a charm and the results are quite amazing.</p><p>In wordpress we got problems implementing this because plugins added their own <code>js</code> and <code>css</code> files at will. <a
href="http://omninoggin.com/wordpress-plugins/wp-minify-wordpress-plugin/"><acronym
title="WordPress">WP</acronym>-Minify</a> from Thaya Kareeson came to save our souls but we got some misbehaving plugins that still adding <code>link</code> and <code>script</code> tags by echoing to the page.</p><p>Fortunately, this new version preprocesses the output thus gathering any inline style/script reference and adding it to a temporary file that is included in the minification process.</p><p>I got tricked there because voting badges and other stuff uses inline <code>script</code> tags to generate the badge. <acronym
title="WordPress">WP</acronym>-Minify&#8217;s preprocessing <strike>fu</strike>freaked me up because this <code>script</code> tag depended on <code>the_permalink()</code> function from WordPress thus not generating the correct output on the temporary file created. Before I started freaking out I realized that the plugin&#8217;s configuration page had an script (and style) blacklist. Just added the <code>src</code> url (without the querystring) and everything worked like a charm!</p><p>Nice job <a
href="http://omninoggin.com/">Thaya</a>!</p><p>No related posts.</p>]]></content:encoded> <wfw:commentRss>http://www.heavyworks.net/blog/posts/wp-minifys-new-version-vanished-wordpress-http-requests-issue/feed</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>So your PHP headers are already sent, but you sent nothing?</title><link>http://www.heavyworks.net/blog/posts/so-your-php-headers-are-already-sent-but-you-sent-nothing</link> <comments>http://www.heavyworks.net/blog/posts/so-your-php-headers-are-already-sent-but-you-sent-nothing#comments</comments> <pubDate>Fri, 13 Feb 2009 03:56:57 +0000</pubDate> <dc:creator>Jan Seidl</dc:creator> <category><![CDATA[Coding]]></category> <category><![CDATA[close tag]]></category> <category><![CDATA[php]]></category> <guid
isPermaLink="false">http://www.heavyworks.net/?p=189</guid> <description><![CDATA[So you are coding and your transfer your files to your production server via SVN or FTP and then you start getting some &#8220;Warning: Cannot modify header information &#8211; headers already sent&#8221; errors. Well, this is not good indeed. This errors happens when you send a header command and has already outputted text to your [...]
No related posts.]]></description> <content:encoded><![CDATA[<p>So you are coding and your transfer your files to your production server via <acronym
title="Subversion">SVN</acronym> or <acronym
title="File Transfer Protocol">FTP</acronym> and then you start getting some &#8220;Warning: Cannot modify header information &#8211; headers already sent&#8221; errors. Well, this is not good indeed.</p><p>This errors happens when you send a <code>header</code> command and has already outputted text to your output buffer (generally, the browser). Then you <code>grep</code> your code for misleft debugging <code>print</code>s, <code>echo</code>s, <code>print_r</code>s and <code>var_dump</code>s but they are gone or commented.</p><p>Oh yeah, somehow some data were added during the transfer somewhere in your source files. Great! Now some cool action!<br
/> <span
id="more-189"></span><br
/> <strong>DON&#8217;T PANIC</strong><br
/> As the 1<super>st</super> rule of code debugging, read the error message.</p><blockquote><p> Warning: Cannot modify header information &#8211; headers already sent by (output started at /var/www/projects/&#8230;/app/models/Keyword.php:168) in /var/www/&#8230;/app/lib/AppController.class.php on line 421</p></blockquote><p>It is all there. Notice the part where it says &#8220;output started at&#8221;. This tells you where to look for the added ghost data, the file and the line. Couldn&#8217;t be easier, could it? Just go to the line and trigger your <code>home</code> and <code>end</code> keys and the cursor will reveal the menace. Be ruthless! Just remove them and reload.</p><p>The second part tells you here your <code>header</code> command was triggered, again, file and line.</p><p>Some people (like people from Zend) tells users to never mind the php close tag <code>?&gt;</code> so you don&#8217;t get bothered by these errors. This is due <acronym
title="PHP: Hypertext Preprocessor">PHP</acronym> ignoring spaces within his enclosure tags but it prints the spaces out of them so if you don&#8217;t close the tag, there will be no tags out of them.</p><p>About this discussion, I choose keeping the close tag. As I said at the debate in a <a
href="http://www.heavyworks.net/posts/truths-and-myths-on-the-web-development-world/" title="Truths and myths on the web development world">previous article</a>: <em>&#8220;Its not needed, ok. But it exists (and it is part of the code structure) so it shall be used.&#8221;</em> and <em>&#8220;If your <acronym
title="File Transfer Protocol">FTP</acronym> or IDE or ANYTHING puts unwanted data on your code, switch your application.  Accidental white spaces. Accident happens when errors happens. A stable code/environment shall not have &#8216;accidents&#8217;&#8221;</em>, but if you do, just read the error code and clean it up.</p><p>No related posts.</p>]]></content:encoded> <wfw:commentRss>http://www.heavyworks.net/blog/posts/so-your-php-headers-are-already-sent-but-you-sent-nothing/feed</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Quick Tip: Do you miss the target?</title><link>http://www.heavyworks.net/blog/posts/quick-tip-do-you-miss-the-target</link> <comments>http://www.heavyworks.net/blog/posts/quick-tip-do-you-miss-the-target#comments</comments> <pubDate>Thu, 05 Feb 2009 21:10:51 +0000</pubDate> <dc:creator>Jan Seidl</dc:creator> <category><![CDATA[Coding]]></category> <category><![CDATA[javascript]]></category> <category><![CDATA[jquery]]></category> <category><![CDATA[unobstrusive]]></category> <guid
isPermaLink="false">http://www.heavyworks.net/?p=181</guid> <description><![CDATA[Opening links in a new window was once quick and easy but since the target="_blank" options on a links have died (if you didn&#8217;t knew, I&#8217;m very sorry to be the one telling you this) the only way left was the javascript way. The click event on a link cannot be anymore traced by the [...]
No related posts.]]></description> <content:encoded><![CDATA[<p>Opening links in a new window was once quick and easy but since the <code>target="_blank"</code> options on <code>a</code> links have died (if you didn&#8217;t knew, I&#8217;m very sorry to be the one telling you this) the only way left was the javascript way.<br
/> <span
id="more-181"></span><br
/> The <code>click</code> event on a link cannot be anymore traced by the <code>onclick</code> parameter on the <code>a</code> tag because all the <code>on*</code> events have died too (I know, it&#8217;s a massacre!) so I&#8217;ll take <a
href="http://snipplr.com/view/8733/jquery-open-external-link-in-new-window/" title="jQuery open external link in new window">this example</a> for basis.</p><p>We&#8217;ll use <a
href="http://www.jquery.com">JQuery</a>&#8216;s selectors to get the links we want.</p><p><em>All external links</em></p><p><em><strong>UPDATED: As WordPress makes all links absolute this code got useless. I&#8217;ve updated it now to check additionally if the link <a
href="http://api.jquery.com/not/">does not</a> <a
href="http://api.jquery.com/attribute-starts-with-selector/">starts with</a> the current domain. I&#8217;ve tested it and it worked!</strong></em></p><p><em>NOTE: I&#8217;ve searched for a shorter form where starts-with and negation could be applied together. If someone has a better solution, please share!</em></p><div
class="wp_syntax"><div
class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ready</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> domain <span style="color: #339933;">=</span> window.<span style="color: #660066;">location</span>.<span style="color: #660066;">host</span><span style="color: #339933;">;</span>
&nbsp;
    $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;a[href^='http://']&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">not</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;[href^='http://&quot;</span><span style="color: #339933;">+</span>domain<span style="color: #339933;">+</span><span style="color: #3366CC;">&quot;']&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>ev<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        ev.<span style="color: #660066;">preventDefault</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        window.<span style="color: #000066;">open</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">href</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div><p><em>All links from a div with &#8216;#id_div&#8217; <code>id</code> attribute</em></p><div
class="wp_syntax"><div
class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ready</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'div#id_div a'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">bind</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'click'</span><span style="color: #339933;">,</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>ev<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        ev.<span style="color: #660066;">preventDefault</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        window.<span style="color: #000066;">open</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">href</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div><p><em>NOTE: I&#8217;m using <code>ev.preventDefault()</code> rather than return false to follow JQuery pattern. Just a good practice.</em><br
/> <em>NOTE: <code>ev</code> is just a variable name I gave. You may change it to suit your needs.</em></p><p>Any more ideas?</p><p>No related posts.</p>]]></content:encoded> <wfw:commentRss>http://www.heavyworks.net/blog/posts/quick-tip-do-you-miss-the-target/feed</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Quick Tip: JavaScript integers parsing</title><link>http://www.heavyworks.net/blog/posts/quick-tip-javascript-integers-parsing</link> <comments>http://www.heavyworks.net/blog/posts/quick-tip-javascript-integers-parsing#comments</comments> <pubDate>Fri, 30 Jan 2009 16:59:29 +0000</pubDate> <dc:creator>Jan Seidl</dc:creator> <category><![CDATA[Coding]]></category> <category><![CDATA[integer]]></category> <category><![CDATA[javascript]]></category> <category><![CDATA[numbers]]></category> <category><![CDATA[octal]]></category> <guid
isPermaLink="false">http://www.heavyworks.net/?p=178</guid> <description><![CDATA[I&#8217;ve came across a strange problem when trying to parse date parts (2009 01 21) as integers in a form validation script. Somehow my month being parsed as 0 (zero) and not as 1 (one) as supposed to be. Strange. I&#8217;ve googled around and discovered that JavaScript&#8217;s parseInt support different (not so many) number bases [...]
No related posts.]]></description> <content:encoded><![CDATA[<p>I&#8217;ve came across a strange problem when trying to parse date parts (2009 01 21) as integers in a form validation script. Somehow my month being parsed as 0 (zero) and not as 1 (one) as supposed to be. Strange. I&#8217;ve googled around and discovered that JavaScript&#8217;s <code><a
href="http://www.w3schools.com/jsref/jsref_parseInt.asp">parseInt</a></code> support different (not so many) number bases and by default it &#8220;guesses&#8221; the base you are trying to work.</p><p>Sure, he found the &#8220;01&#8243; and thought &#8220;Oh yeah babe, it&#8217;s an octal number!&#8221; &#8212; wrong my friend, it&#8217;s just a zero-padded number, sorry disappointing.</p><p>So, I had to supply the second argument called <code>radix</code> as 10 (decimal) that is indeed the base you are going to use. Setting this makes <code>parseInt</code> to respect you instead of having his free-will.</p><p>So I &#8216;ve got:</p><div
class="wp_syntax"><div
class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> _orderDateMonth <span style="color: #339933;">=</span> parseInt<span style="color: #009900;">&#40;</span>$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#survey_order_date_month'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span><span style="color: #CC0000;">10</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// decimal base!</span></pre></div></div><p><em>NOTE: The dollar sign ($) and <code>.val()</code> are specific <a
href="http://jquery.com/">JQuery</a> functions.</em></p><p><em>NOTE: I personally hate when people break up the date parts into different <code>input</code>s. If you are already going to use JavaScript, implement a damn date-picker!</em></p><p>No related posts.</p>]]></content:encoded> <wfw:commentRss>http://www.heavyworks.net/blog/posts/quick-tip-javascript-integers-parsing/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> </channel> </rss>
