<?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>Christian Schenk&#187; code</title>
	<atom:link href="http://www.christianschenk.org/blog/tag/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.christianschenk.org</link>
	<description>Writing about my experiences with technology and all different kinds of projects and experiments</description>
	<lastBuildDate>Sun, 29 Aug 2010 09:08:16 +0000</lastBuildDate>
	
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Profiling with CPU-Sampler</title>
		<link>http://www.christianschenk.org/blog/profiling-cpu-sampler/</link>
		<comments>http://www.christianschenk.org/blog/profiling-cpu-sampler/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 10:12:40 +0000</pubDate>
		<dc:creator>Christian Schenk</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[cpu sampler]]></category>
		<category><![CDATA[opengl]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[profiling]]></category>
		<category><![CDATA[xcode]]></category>

		<guid isPermaLink="false">http://www.christianschenk.org/?p=734</guid>
		<description><![CDATA[Apple&#8217;s Xcode comes with a neat profiling tool called CPU Sampler. It helps you identifying time consuming code blocks in your software and is really handy if you need to optimize for optimal performance.
Just recently I tried rewriting OpenGL&#8217;s routines that handle matrix calculations as part of a lecture at the university. Pretty soon I [...]]]></description>
			<content:encoded><![CDATA[<p>Apple&#8217;s Xcode comes with a neat profiling tool called <em>CPU Sampler</em>. It helps you identifying time consuming code blocks in your software and is really handy if you need to optimize for optimal performance.</p>
<p>Just recently I tried rewriting OpenGL&#8217;s routines that handle matrix calculations as part of a lecture at the university. Pretty soon I came to the conclusion, that I had to optimize my code if I wanted to compete with the implementation provided by OpenGL.</p>
<p>This post presents at quick look at <em>CPU Sampler</em> which helped me making well-founded decisions resulting in a faster implementation.</p>
<p><span id="more-734"></span></p>
<h2>Howto</h2>
<p>Once you&#8217;ve developed your software with Xcode and want to profile it using <em>CPU Sampler</em>, all you have to do is to click on Run &#8211; Run with Performance Tool &#8211; CPU Sampler. This will start the tool and run your application; you can start and stop the recording as you see fit.</p>
<p>As soon as you end your application you can have a look at the samples collected during the last run. This is the interesting part because you can review how long a certain function was running and the percentage tells you how long this took compared to the overall run.</p>
<p>Try playing around with the various options. In most situations you can stick with the defaults but there&#8217;re more interesting things to look at if you want to. For example try changing the <em>Active thread</em> from <em>All threads</em> to something else and the view will show the corresponding samples only.</p>
<h2>Example</h2>
<p>As I said, I tried rewriting OpenGL&#8217;s routines that handle matrix calculations. This was meant as an exercise to understand the operations needed that changed the matrices. Of course, the implementation was way slower than OpenGL and I should try speeding it up.</p>
<p>Using <em>CPU Sampler</em> I immediately identified a bottleneck and a major difference between my implementation and the one that comes with OpenGL. The slow part of my code could be found in repeated calls to <code>cos</code> and <code>sin</code>. Since OpenGL seems to work with the libraries of my graphics card directly I guess it tries to do certain computations there.</p>
<p>What I now did was substituting the calls to <code>cos</code> and <code>sin</code> with code that used a lookup table to retrieve precalculated values. This resulted in a major performance boost &#8211; still, OpenGL&#8217;s code is twice as fast as my one.</p>
<p>Have a look at the following screenshots. They show a run using OpenGL&#8217;s implementation of matrix manipulations, my own and an optimized version of my own implementation. Comparing the naive and optimized version of my code clearly shows that the optimized variant doesn&#8217;t spent much time calculating <code>cos</code> and <code>sin</code>.</p>
<div style="white-space:nowrap">
<a href="/wp-content/uploads/opengl.png" title="OpenGL" class="thickbox" rel="gallery-opengl"><img src="/wp-content/uploads/opengl-150x150.png" alt="OpenGL" /></a><a href="/wp-content/uploads/our_impl.png" title="Own implementation" class="thickbox" rel="gallery-opengl"><img src="/wp-content/uploads/our_impl-150x150.png" alt="Own implementation" /></a><a href="/wp-content/uploads/our_impl_opt.png" title="Own implementation optimized" class="thickbox" rel="gallery-opengl"><img src="/wp-content/uploads/our_impl_opt-150x150.png" alt="Own implementation optimized" /></a>
</div>
<h2>Conclusion</h2>
<p>I wanted to show that using a profiling tool like <em>CPU Sampler</em> that comes with Apple&#8217;s Xcode may make your life much easier if you&#8217;re trying to optimize your application. This helps you to make wise decisions when it comes to optimizing code so you don&#8217;t have to obfuscate your software with hard to read code blocks that have a very little effect regarding performance.</p>
<p>It&#8217;s nice to see that Apple ships tools like this with its IDE. Have a look at the other performance tools and you&#8217;ll be amazed how many cools things Xcode is capable of &#8211; things you wouldn&#8217;t even dream about in other IDE&#8217;s.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.christianschenk.org/blog/profiling-cpu-sampler/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Building your own Fetch as Googlebot</title>
		<link>http://www.christianschenk.org/blog/building-your-own-fetch-as-googlebot/</link>
		<comments>http://www.christianschenk.org/blog/building-your-own-fetch-as-googlebot/#comments</comments>
		<pubDate>Mon, 28 Dec 2009 06:55:40 +0000</pubDate>
		<dc:creator>Christian Schenk</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[bot]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[webmaster]]></category>

		<guid isPermaLink="false">http://www.christianschenk.org/?p=723</guid>
		<description><![CDATA[Just recently Google announced a great feature as part of the Webmaster Tools: you can fetch your site with the Googlebot. At first I thought they would reveal what content gets extracted from the site and how they might proceed from there but they just seem to crawl your site, showing you the HTTP header [...]]]></description>
			<content:encoded><![CDATA[<p>Just recently Google <a href="http://googlewebmastercentral.blogspot.com/2009/10/fetch-as-googlebot-and-malware-details.html">announced</a> a great feature as part of the <em>Webmaster Tools</em>: you can fetch your site with the Googlebot. At first I thought they would reveal what content gets extracted from the site and how they might proceed from there but they just seem to crawl your site, showing you the HTTP header fields and the site&#8217;s content.</p>
<p>In this post I&#8217;d like to present some Java code using the latest and greatest version of <a href="http://hc.apache.org/httpcomponents-client/">HttpClient</a> that allows you to crawl any site, have a look at the HTTP header fields, the site&#8217;s content and measure how long it took to download the site. It&#8217;s almost the same what Google&#8217;s feature does.</p>
<p>The Eclipse project with the code for this post can be downloaded as <a href="http://data.christianschenk.org/building-your-own-fetch-as-googlebot/FetchAsGooglebot.tar.gz">tar.gz</a> or <a href="http://data.christianschenk.org/building-your-own-fetch-as-googlebot/FetchAsGooglebot.zip">zip</a>. You can browse the code online <a href="http://data.christianschenk.org/building-your-own-fetch-as-googlebot/xref/">here</a>.</p>
<p><span id="more-723"></span></p>
<h2>Implementation</h2>
<p>The team building HttpClient does a great job improving and perfecting the software. I really like using this fully featured client implementation when it comes to retrieving data via HTTP. It&#8217;s easy to set up and configuring as you see fit is a snap.</p>
<p>I&#8217;ve used it for this little project too because I only needed four lines of code to get it running. In my opinion the HttpClient API can&#8217;t get any better than this. Check out the following code:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">HttpClient httpclient <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> DefaultHttpClient<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
HttpGet httpget <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> HttpGet<span style="color: #009900;">&#40;</span>url<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
HttpResponse response <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">httpclient</span>.<span style="color: #006633;">execute</span><span style="color: #009900;">&#40;</span>httpget<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
HttpEntity entity <span style="color: #339933;">=</span> response.<span style="color: #006633;">getEntity</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Once you&#8217;ve done that you can use the <code>HttpResponse</code> and <code>HttpEntity</code> objects to retrieve the HTTP header fields and the downloaded content; the <code>EntityUtils</code> come in handy here.</p>
<p>If you run my implementation it prints the following information: HTTP return code, HTTP header fields, the downloaded content and the time it took to execute the request. This is similar to the information offered by Google&#8217;s <em>Fetch as Googlebot</em> feature. As you can see, it&#8217;s pretty easy implementing it on your own if you haven&#8217;t got special requirements.</p>
<h2>Conclusion</h2>
<p>Nevertheless, Google&#8217;s <em>Fetch as Googlebot</em> feature is a really nice thing and I think they&#8217;ll expand its features as a greater part of the <em>Webmaster Tools</em>. In this post I wanted to show you that it&#8217;s pretty easy building a similar tool on your own. By the way, using e.g. the <em>Web developer</em> plugin for Firefox might be good alternative too.</p>
<p>Note, that Google probably invested a lot more work to get this feature rolling and it&#8217;s very likely that it wasn&#8217;t <em>that</em> easy for them to make it part of the Webmaster Tools. In this regard this post might make you think that this feature was an <em>easy one</em> &#8211; you guessed it, that&#8217;s probably not the case.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.christianschenk.org/blog/building-your-own-fetch-as-googlebot/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WordPress: is_child function</title>
		<link>http://www.christianschenk.org/blog/wordpress-is_child-function/</link>
		<comments>http://www.christianschenk.org/blog/wordpress-is_child-function/#comments</comments>
		<pubDate>Sun, 20 Dec 2009 06:10:48 +0000</pubDate>
		<dc:creator>Christian Schenk</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[function]]></category>
		<category><![CDATA[is_child]]></category>
		<category><![CDATA[is_tree]]></category>
		<category><![CDATA[parent]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://www.christianschenk.org/?p=735</guid>
		<description><![CDATA[Every once in a while I would like to test whether the current page is a descendant of another page. This is particularly useful if you want to display certain content on a subset of your pages only. Although the Codex suggests a similar is_tree function I would like to present an extended version here.
I&#8217;ve [...]]]></description>
			<content:encoded><![CDATA[<p>Every once in a while I would like to test whether the current page is a descendant of another page. This is particularly useful if you want to display certain content on a subset of your pages only. Although the <a href="http://codex.wordpress.org/">Codex</a> suggests a similar <code>is_tree</code> function I would like to present an extended version here.</p>
<p>I&#8217;ve packaged the functionality inside a WordPress plugin called is_child that you can download <a href="http://data.christianschenk.org/wordpress-is_child-function/ischild.php.zip">here</a>. Unzip it, upload it to <code>wp-content/plugins</code> and activate the plugin.</p>
<p><span id="more-735"></span></p>
<h2>Coding is_child</h2>
<p>Doing a quick web search brings up tons of sites providing some sort of <code>is_child</code> or <code>is_tree</code> function. Most of the time it&#8217;s something 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> is_child<span style="color: #009900;">&#40;</span><span style="color: #000088;">$parent</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">global</span> <span style="color: #000088;">$post</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">return</span> <span style="color: #000088;">$post</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">post_parent</span> <span style="color: #339933;">==</span> <span style="color: #000088;">$parent</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This is great and a pretty nice solution. I&#8217;ve taken this approach and extended it with the following functionality:</p>
<ul>
<li>by default we&#8217;ll retrieve all parent pages up to the root node and test whether the current page is part of this tree. This behavior can be disabled though.</li>
<li>you can supply the name (<em>slug</em>) of a post/page instead of the ID and the function will look it up for you.</li>
</ul>
<p>All this combined with some error checking makes a great idea even better. Just have a look at the code if you would like to know more about the exact implementation.</p>
<h2>Conclusion</h2>
<p>We&#8217;ve seen that it&#8217;s very easy to test whether the current page is a child of another page or part of a certain tree in your page hierarchy. Packaging this into a plugin or placing the necessary code into your theme&#8217;s <code>functions.php</code> allows you to display certain content on particular pages only. In case you&#8217;re using the <a href="http://wordpress.org/extend/plugins/widget-logic/">Widget logic</a> plugin you now can display widgets on pages belonging to a particular subtree of your pages only, which is great.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.christianschenk.org/blog/wordpress-is_child-function/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Ideas about clean if statements</title>
		<link>http://www.christianschenk.org/blog/ideas-clean-if-statements/</link>
		<comments>http://www.christianschenk.org/blog/ideas-clean-if-statements/#comments</comments>
		<pubDate>Fri, 18 Dec 2009 03:40:51 +0000</pubDate>
		<dc:creator>Christian Schenk</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[clean]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[ideas]]></category>
		<category><![CDATA[if]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[statements]]></category>
		<category><![CDATA[Thoughts]]></category>

		<guid isPermaLink="false">http://www.christianschenk.org/?p=59</guid>
		<description><![CDATA[If you&#8217;re reading a lot of code you may get to the point where you&#8217;d like it to be clean, so it&#8217;s easier for you to read. There&#8217;re a lot of resources about the beauty of code around and in this post I&#8217;d like to share some ideas about writing concise if statements.
Although these ideas [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re reading a lot of code you may get to the point where you&#8217;d like it to be clean, so it&#8217;s easier for you to read. There&#8217;re a lot of resources about the beauty of code around and in this post I&#8217;d like to share some ideas about writing concise <code>if</code> statements.</p>
<p>Although these ideas may apply to a lot of different programming languages I chose to give examples written in Java, PHP or Python. There should be no problem to translate this into other, similar languages.</p>
<p><span id="more-59"></span></p>
<h2>Indentation hell</h2>
<p>A lot of years ago I read a text file describing the preferred coding style for the Linux kernel: it said that you&#8217;re screwed anyway if you need more than three levels of indentation. This stems from hackers using a screen resolution that allows a certain number of characters only. Writing code that uses a lot of nested statements causes the problem that you can&#8217;t read everything on a 80&#215;25 terminal; wrapping lines may make things worse.</p>
<p>Back then the solution was to either increase the screen&#8217;s resolution <em>or</em> write clean code. Even today the latter is a good idea not only when writing code but maybe configuration files in general. Imagine a sysadmin in the server room with an old monitor only &#8211; he&#8217;ll thank you that you formatted the comments with a text width of 80 characters or less.</p>
<p>Let&#8217;s have a look at an example like the following. You&#8217;ll notice that I&#8217;ve use four levels of indentation: a for loop, an if statement, another for loop and another if statement.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> x<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">==</span> y<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> j <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> j <span style="color: #339933;">&lt;</span> z<span style="color: #339933;">;</span> j<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>j <span style="color: #339933;">==</span> a<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// do something special</span>
        <span style="color: #666666; font-style: italic;">// ...</span>
      <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>We can spot this pattern by looking at it&#8217;s tail: a lot of closing curly brackets. Refactoring this snippet consists of splitting the code into various functions and calling them at the right time. One solution might look like so:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> a<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> x<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">==</span> y<span style="color: #009900;">&#41;</span> b<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: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> b<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> j <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> j <span style="color: #339933;">&lt;</span> z<span style="color: #339933;">;</span> j<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>j <span style="color: #339933;">==</span> a<span style="color: #009900;">&#41;</span> do_something_special<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: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> do_something_special<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;">// do something special</span>
  <span style="color: #666666; font-style: italic;">// ...</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Now, the code is much easier to read and unit testing it will be more fun too. Don&#8217;t be afraid of adding <em>extra</em> functions into your program when you could write it all into one method/function. The latter is harder to maintain and rest assured that more method/function calls won&#8217;t add a serious performance penalty to your application in any way.</p>
<h2>Inverting</h2>
<p>It&#8217;s likely that you&#8217;ve seen a method that starts with an if statement, almost all the method&#8217;s code is inside that statement and at the end of the method you find the else block with only one statement in it, maybe some error handling code.</p>
<p>Instead of writing if statements that span multiple pages and contain lots and lots of code the following technique allows you to have the if statement on one line. As discussed above this avoids an unnecessary level of indentation as well.</p>
<p>Let&#8217;s have a look at an example: a simple method containing an if statement with another if statement which holds the real code of the method.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> doIt<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>something <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: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>something_else <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: #666666; font-style: italic;"># do something...
</span>      <span style="color: #666666; font-style: italic;"># ...
</span>    <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
    throw <span style="color: #000000; font-weight: bold;">new</span> Exception<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: #009900;">&#125;</span></pre></div></div>

<p>Simply by inverting the if statements we can write them on one line, producing the following, much cleaner code:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> doIt<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>something <span style="color: #339933;">==</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span> throw <span style="color: #000000; font-weight: bold;">new</span> Exception<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span>something_else <span style="color: #339933;">==</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">return</span><span style="color: #339933;">;</span>
  <span style="color: #666666; font-style: italic;"># do something...
</span>  <span style="color: #666666; font-style: italic;"># ...
</span><span style="color: #009900;">&#125;</span></pre></div></div>

<p>Again, not just the statement but the whole method is easier to read. If you&#8217;re checking preconditions, this is the way to go. This also prevents the indentation hell mentioned above.</p>
<h2>Splitting</h2>
<p>Speaking of checks for the preconditions of certain methods, one might tend to put all checks into one single if statement. This may save you from e.g. writing code to throw an exception more than once but may result in a hard to understand if statement.</p>
<p>I recommend writing if statements that test only one or two conditions. Have a look at the following code which contains a giant if statement.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> method<span style="color: black;">&#40;</span>a, b, c<span style="color: black;">&#41;</span>:
  <span style="color: #ff7700;font-weight:bold;">if</span> a <span style="color: #66cc66;">&lt;</span>= <span style="color: #ff4500;">10</span> <span style="color: #ff7700;font-weight:bold;">or</span> a <span style="color: #66cc66;">&gt;</span>= <span style="color: #ff4500;">20</span> <span style="color: #ff7700;font-weight:bold;">or</span> \
     b == <span style="color: #008000;">False</span> <span style="color: #ff7700;font-weight:bold;">or</span> \
     c == <span style="color: #483d8b;">'unknown'</span>:
    <span style="color: #ff7700;font-weight:bold;">raise</span> SomeException<span style="color: black;">&#40;</span><span style="color: #483d8b;">'Invalid arguments'</span><span style="color: black;">&#41;</span>
  <span style="color: #808080; font-style: italic;"># do something...</span>
  <span style="color: #808080; font-style: italic;"># ...</span></pre></div></div>

<p>We could argue that the code is pretty clean and easy to understand. True in this case, but the semantics aren&#8217;t obvious. What about introducing two more methods and raising more specific exceptions? Would result in this:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> method<span style="color: black;">&#40;</span>a, b, c<span style="color: black;">&#41;</span>:
  <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #ff7700;font-weight:bold;">not</span> inRange<span style="color: black;">&#40;</span>a, <span style="color: #ff4500;">10</span>, <span style="color: #ff4500;">20</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">raise</span> SomeException<span style="color: black;">&#40;</span><span style="color: #483d8b;">'Argument a is out of bounds'</span><span style="color: black;">&#41;</span>
  <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #ff7700;font-weight:bold;">not</span> isValid<span style="color: black;">&#40;</span>b<span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">or</span> <span style="color: #ff7700;font-weight:bold;">not</span> isValid<span style="color: black;">&#40;</span>c<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">raise</span> SomeException<span style="color: black;">&#40;</span><span style="color: #483d8b;">'Argument b or c are invalid'</span><span style="color: black;">&#41;</span>
  <span style="color: #808080; font-style: italic;"># do something...</span>
  <span style="color: #808080; font-style: italic;"># ...</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> inRange<span style="color: black;">&#40;</span>a, start, end<span style="color: black;">&#41;</span>:
  <span style="color: #ff7700;font-weight:bold;">return</span> a <span style="color: #66cc66;">&gt;</span>= start <span style="color: #ff7700;font-weight:bold;">and</span> a <span style="color: #66cc66;">&lt;</span>= end
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> isValid<span style="color: black;">&#40;</span>a<span style="color: black;">&#41;</span>:
  <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #ff7700;font-weight:bold;">not</span> <span style="color: black;">&#40;</span> a == <span style="color: #008000;">False</span> <span style="color: #ff7700;font-weight:bold;">or</span> a == <span style="color: #483d8b;">'unknown'</span> <span style="color: black;">&#41;</span></pre></div></div>

<p>This may bloat your code a little bit but helps you reading the code almost like a sentence. Splitting one large if statement into smaller ones may result in sensible error messages too. And the introduction of small helper methods makes unit testing fun again.</p>
<h2>Sorting</h2>
<p>If you&#8217;re using the previous technique &#8211; splitting a single if statement into smaller, more concise portions &#8211; you should consider the order of the if statements. Let&#8217;s think about a simple example: in a <a href="/blog/friday-13th-joda-time/">recent post</a> I tried finding occurrences of Friday the 13th dates by iterating over a given time span. The method looked like so:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #666666; font-style: italic;">/* ... */</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    date <span style="color: #339933;">=</span> date.<span style="color: #006633;">plusDays</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>date.<span style="color: #006633;">getDayOfMonth</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!=</span> <span style="color: #cc66cc;">13</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">continue</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>date.<span style="color: #006633;">getDayOfWeek</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!=</span> DateTimeConstants.<span style="color: #006633;">FRIDAY</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">continue</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// ...</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The two if statements test whether the current day is a Friday the 13th date. First checking whether the current day is the 13th day of a month speeds things up a little bit because we&#8217;ll only check whether this day happens to be a friday &#8211; the other way around would be more expensive in terms of performance.</p>
<p>This technique also applies when your if statements call <em>expensive</em> methods to test a certain condition. You may want to call the ones with the least overhead first thus reducing the time spent in your if statements.</p>
<h2>Conclusion</h2>
<p>In this post I presented some simple solutions that should help you writing cleaner, better code regarding if statements. Following these rules will make your code much easier to read and to maintain. Just give it a try and you&#8217;ll definitely notice the positive difference.</p>
<p>Sure, I haven&#8217;t given any references to real projects helping you to verify that the examples given in this post exist in real projects. I think searching in real projects for code like the above shouldn&#8217;t be much of a problem. And I&#8217;m pretty sure you&#8217;ll agree on this.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.christianschenk.org/blog/ideas-clean-if-statements/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hot math: twin and sexy prime numbers</title>
		<link>http://www.christianschenk.org/blog/math-twin-sexy-prime-numbers/</link>
		<comments>http://www.christianschenk.org/blog/math-twin-sexy-prime-numbers/#comments</comments>
		<pubDate>Mon, 14 Dec 2009 05:12:06 +0000</pubDate>
		<dc:creator>Christian Schenk</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[numbers]]></category>
		<category><![CDATA[primes]]></category>
		<category><![CDATA[sexy]]></category>
		<category><![CDATA[twin]]></category>

		<guid isPermaLink="false">http://www.christianschenk.org/?p=722</guid>
		<description><![CDATA[Just recently I discovered that there&#8217;s something called sexy prime numbers. I read about twin primes but hadn&#8217;t heard the other term before. The concept is pretty simple: take a prime number and check whether the next prime minus the first one results in a certain number, e.g. 2 for twin primes or 6 for [...]]]></description>
			<content:encoded><![CDATA[<p>Just recently I discovered that there&#8217;s something called <em>sexy</em> prime numbers. I read about twin primes but hadn&#8217;t heard the other term before. The concept is pretty simple: take a prime number and check whether the next prime minus the first one results in a certain number, e.g. 2 for twin primes or 6 for sexy primes. This post presents a simple solution to calculate arbitrary combinations of prime number pairs, triplets, etc.</p>
<p>The Eclipse project with the code for this post can be downloaded as <a href="http://data.christianschenk.org/math-twin-sexy-primes/PrimeGroups.tar.gz">tar.gz</a> or <a href="http://data.christianschenk.org/math-twin-sexy-primes/PrimeGroups.zip">zip</a>. You can browse the code online <a href="http://data.christianschenk.org/math-twin-sexy-primes/xref/">here</a>.</p>
<p><span id="more-722"></span></p>
<h2>Preliminary</h2>
<p>It&#8217;s likely that you already know how to calculate prime numbers but I&#8217;d like to show you a feasible approach anyway. The idea is based on the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">sieve of Eratosthenes</a>: starting with the number 2, use it as a prime number if it isn&#8217;t divisible by any other prime number otherwise discard it. The advantage: easy to implement, the disadvantage: not that fast.</p>
<p>If we&#8217;d like to calculate the prime numbers starting with 2, up to 500 we could write the following code snippet:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> <span style="color: #cc66cc;">500</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>isDivisibleByPrime<span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">continue</span><span style="color: #339933;">;</span>
  primes.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This implementation is simple yet fast enough for my purposes. Note that using Java&#8217;s primitive types it&#8217;s not possible to find prime numbers of arbitrary length; more work is required here if you want to do that.</p>
<h2>Arbitrary groups of primes</h2>
<p>What I call a group here is a set of prime numbers differing by a particular number. One example would be triplets of prime number that differ by six, called the sexy prime triplets. You could think of many combinations, i.e. twins, triplets or quadruplets where the numbers differ by e.g. 2, 3 or 6.</p>
<p>The code that finds these sets of prime numbers is straight forward. It generates a list with prime numbers, searches for a given pattern &#8211; e.g. sexy prime triplets &#8211; and prints the results. By changing the parameters you can make up any combination you like but keep in mind that some will return an empty result.</p>
<p>Check out the file <code>PrimeGroups</code>, specifically the top of the <code>main</code> method. Try chaning the paramters <code>start</code>, <code>end</code>, <code>amount</code> and <code>distance</code>. Did you expect to get that many results for a certain pattern? It can be quite entertaining changing <code>amount</code> and <code>distance</code>, don&#8217;t you think?</p>
<h2>Conclusion</h2>
<p>It&#8217;s easy and interesting to search prime numbers that match certain criteria. Have a look at the code and you&#8217;ll see that the implementation is pretty easy and doesn&#8217;t require extra coding skills if you don&#8217;t want to search for particularly large primes. Finally, it&#8217;s a nice exercise &#8211; even as a math novice &#8211; thinking about numbers and prime numbers in particular.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.christianschenk.org/blog/math-twin-sexy-prime-numbers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Friday the 13th with Joda Time</title>
		<link>http://www.christianschenk.org/blog/friday-13th-joda-time/</link>
		<comments>http://www.christianschenk.org/blog/friday-13th-joda-time/#comments</comments>
		<pubDate>Tue, 08 Dec 2009 07:15:52 +0000</pubDate>
		<dc:creator>Christian Schenk</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[13th]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[date]]></category>
		<category><![CDATA[friday]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[joda time]]></category>
		<category><![CDATA[time]]></category>

		<guid isPermaLink="false">http://www.christianschenk.org/?p=114</guid>
		<description><![CDATA[I&#8217;ve always wanted to try Joda Time and in this post I&#8217;d like to present some code that finds Friday the 13th dates. Wouldn&#8217;t it be interesting to know when the next Friday the 13th is or which year has got the most occurrences of this particular day?
The Eclipse project with the code for this [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve always wanted to try <a href="http://joda-time.sourceforge.net/">Joda Time</a> and in this post I&#8217;d like to present some code that finds <a href="http://en.wikipedia.org/wiki/Friday_the_13th">Friday the 13th</a> dates. Wouldn&#8217;t it be interesting to know when the next <em>Friday the 13th</em> is or which year has got the most occurrences of this particular day?</p>
<p>The Eclipse project with the code for this post can be downloaded as <a href="http://data.christianschenk.org/friday-13th-joda-time/JodaFriday13th.tar.gz">tar.gz</a> or <a href="http://data.christianschenk.org/friday-13th-joda-time/JodaFriday13th.zip">zip</a>. You can browse the code online <a href="http://data.christianschenk.org/friday-13th-joda-time/xref/">here</a>.</p>
<p><span id="more-114"></span></p>
<h2>The code</h2>
<p>Using Joda Time it&#8217;s super easy to iterate over the next days using the <code>plusDays</code> method of <code>DateTime</code>. Finding Friday the 13th dates is straight forward this way. Sure, we could optimize it but Joda Time seems to be really fast so there&#8217;s no need to do this.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> List<span style="color: #339933;">&lt;</span>DateTime<span style="color: #339933;">&gt;</span> getNextNthFriday13th<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">int</span> n<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">final</span> List<span style="color: #339933;">&lt;</span>DateTime<span style="color: #339933;">&gt;</span> fridays <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>DateTime<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  DateTime dt <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">int</span> curN <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span>curN <span style="color: #339933;">&lt;</span> n<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    dt <span style="color: #339933;">=</span> dt.<span style="color: #006633;">plusDays</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>dt.<span style="color: #006633;">getDayOfMonth</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!=</span> <span style="color: #cc66cc;">13</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">continue</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>dt.<span style="color: #006633;">getDayOfWeek</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!=</span> DateTimeConstants.<span style="color: #006633;">FRIDAY</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">continue</span><span style="color: #339933;">;</span>
&nbsp;
    fridays.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> DateTime<span style="color: #009900;">&#40;</span>dt.<span style="color: #006633;">toInstant</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    curN<span style="color: #339933;">++;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">return</span> fridays<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Finding the next year with the most Friday the 13th dates is simple too. Just get the next <em>n</em> occurrences of Friday the 13th and sort them by year to find the one with the highest amount. Another way to solve this is this: just search the next year that has got three Friday the 13th dates and you&#8217;re done. Have a look at the code of <a href="http://data.christianschenk.org/friday-13th-joda-time/xref/org/christianschenk/friday13th/Friday13th.html#62">this method</a> to see my quick solution.</p>
<h2>Conclusion</h2>
<p>It&#8217;s a real joy to use Joda Time because its API has got methods for a lot of use cases. Although I haven&#8217;t done any performance tests yet it seems to be lightning fast. I recommend that you should definitely have a look at it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.christianschenk.org/blog/friday-13th-joda-time/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
