<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[codefixes.com]]></title>
  <link href="http://www.codefixes.com/atom.xml" rel="self"/>
  <link href="http://www.codefixes.com/"/>
  <updated>2017-12-16T15:04:48-06:00</updated>
  <id>http://www.codefixes.com/</id>
  <author>
    <name><![CDATA[Mark Glenn]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Think Functional: Definition of Idempotence]]></title>
    <link href="http://www.codefixes.com/2013/08/think-functional-definition-of-idempotence/"/>
    <updated>2013-08-31T16:16:00-05:00</updated>
    <id>http://www.codefixes.com/2013/08/think-functional-definition-of-idempotence</id>
    <content type="html"><![CDATA[<p>In the most basic of terms, idempotence pertains to the property of certain functions to be applied more than once and always
returning the same result.  While originally a mathematical term, it has since been added into the vocabulary of the computer
science world.  It has been used from discussing the basic paradigm of functional programming, to databases, to web
development.  It has such a wide range of uses, its surprising to me that I only in the past few years started really knowing
what it means.  Let&rsquo;s step back and really think about the tenets of idempotence and what it means to the programmers
of the world.</p>

<!-- more -->


<p>The definition of idempotence varies based on context.  However, stating a function (whether it is a RESTful call,
a function call, or a SQL command) is idempotent usually means that function has the following properties:</p>

<ol>
<li>The function should be referentially transparent.</li>
<li>The function should be reentrant.</li>
<li>The function should not have any side effects.</li>
</ol>


<p>That&rsquo;s the basic definition I could find on Wikipedia, but it makes it sound much more complicated than it really needs to
be.  This may be because the principles of Computer Science are so intertwined with mathematics that we like to discuss
these ideas using equations and complex terminology.  However, the idea of idempotence is easy enough to grasp for
mathematics laymen such as myself.</p>

<h2>The function should be referentially transparent</h2>

<p>Referential transparency of a function suggests that a function call can be replaced with a hardcoded result value without
changing the behavior of the program.  For example, let&rsquo;s say we have a method that calculates the area of a rectangle.
Simple enough to build this using ruby.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="c1"># Calculate the area of a rectangle</span>
</span><span class='line'><span class="k">def</span> <span class="nf">area</span><span class="p">(</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="p">)</span>
</span><span class='line'>  <span class="n">x</span> <span class="o">*</span> <span class="n">y</span>
</span><span class='line'><span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="c1"># Call the area method</span>
</span><span class='line'><span class="n">my_area</span> <span class="o">=</span> <span class="n">area</span><span class="p">(</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">20</span> <span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="nb">puts</span> <span class="n">my_area</span> <span class="c1"># 200</span>
</span></code></pre></td></tr></table></div></figure>


<p>As you can see, a simple call to the area method with x equal to 10 and y equal to 20 will return a result of 200.
We can also see that if we call <code>area( 10, 20 )</code> any amount of times, it will always return that same result.  Knowing
this, we can easily enough replace all that code with this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="c1"># Calculate the area of a rectangle</span>
</span><span class='line'><span class="c1"># def area( x, y )</span>
</span><span class='line'><span class="c1">#   x * y</span>
</span><span class='line'><span class="c1"># end</span>
</span><span class='line'>
</span><span class='line'><span class="c1"># Call the area method</span>
</span><span class='line'><span class="c1"># my_area = area( 10, 20 )</span>
</span><span class='line'><span class="n">my_area</span> <span class="o">=</span> <span class="mi">200</span>
</span><span class='line'>
</span><span class='line'><span class="nb">puts</span> <span class="n">my_area</span> <span class="c1"># 200</span>
</span></code></pre></td></tr></table></div></figure>


<p>Haskell, a functional programming language, has this type of replacement built in since it&rsquo;s built on the idea that a
function should have referential transparency.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='hs'><span class='line'><span class="kr">let</span> <span class="n">area</span> <span class="ow">::</span> <span class="kt">Int</span> <span class="ow">-&gt;</span> <span class="kt">Int</span> <span class="ow">-&gt;</span> <span class="kt">Int</span>
</span><span class='line'>    <span class="n">area</span> <span class="mi">10</span> <span class="mi">20</span> <span class="ow">=</span> <span class="mi">200</span>
</span><span class='line'>    <span class="n">area</span> <span class="n">x</span> <span class="n">y</span> <span class="ow">=</span> <span class="n">x</span> <span class="o">*</span> <span class="n">y</span>
</span><span class='line'>
</span><span class='line'><span class="nf">show</span><span class="p">(</span> <span class="n">area</span> <span class="mi">10</span> <span class="mi">20</span> <span class="p">)</span> <span class="c1">-- &quot;200&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>As we can see here, when we call <code>area 10 20</code> it runs the first method that returns the hard coded value of 200.
Any other values will run the second version of the function.</p>

<h2>The function should be reentrant</h2>

<p>A function is considered reentrant if it can be safely interrupted while in the middle of running and re-executed
before the first pass has completed.  This can happen on a multitasking operating system, which is pretty much every
O/S in existence today.  For example, let&rsquo;s say we have two threads running the same method on a single core machine.
At any time, the operating system can stop the first thread and start running the second.  In the case that the two
threads are executing the same method, the two threads should not clash.  No shared data should be modified that could
cause the first thread to be in an unknown state when it continues executing.  Let&rsquo;s look at an example of a
non-reentrant function</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">string_value</span> <span class="o">=</span> <span class="s2">&quot;&quot;</span>
</span><span class='line'>
</span><span class='line'><span class="k">def</span> <span class="nf">add_to_string</span><span class="p">(</span> <span class="n">line</span> <span class="p">)</span>
</span><span class='line'>  <span class="n">string_value</span> <span class="o">+=</span> <span class="n">line</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1"># Thread interrupted here</span>
</span><span class='line'>
</span><span class='line'>  <span class="n">string_value</span> <span class="o">+=</span> <span class="s2">&quot;</span><span class="se">\n</span><span class="s2">&quot;</span>
</span><span class='line'><span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="n">thread1</span> <span class="o">=</span> <span class="no">Thread</span><span class="o">.</span><span class="n">new</span><span class="p">{</span> <span class="n">add_to_string</span><span class="p">(</span> <span class="s1">&#39;line1&#39;</span> <span class="p">)</span> <span class="p">}</span>
</span><span class='line'><span class="n">thread2</span> <span class="o">=</span> <span class="no">Thread</span><span class="o">.</span><span class="n">new</span><span class="p">{</span> <span class="n">add_to_string</span><span class="p">(</span> <span class="s1">&#39;line2&#39;</span> <span class="p">)</span> <span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="n">thread1</span><span class="o">.</span><span class="n">join</span>
</span><span class='line'><span class="n">thread2</span><span class="o">.</span><span class="n">join</span>
</span><span class='line'>
</span><span class='line'><span class="nb">puts</span> <span class="n">string_value</span> <span class="c1"># &quot;line1line2\n\n&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>As you can see, calling add_to_string on two different threads can cause an unknown state if the method is swapped out
in the middle of execution.  While we&rsquo;d expect <code>line1</code> and <code>line2</code> to be on separate lines, they come out on one.  This
method is considered non-reentrant because it modifies a global state, in this case <code>string_value</code>.</p>

<p>Now, you may believe that reentrant and thread safe are synonymous, but they are different in a very important way.  Let&rsquo;s say
we modified this code to read as the following:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">mutex</span> <span class="o">=</span> <span class="no">Mutex</span><span class="o">.</span><span class="n">new</span>
</span><span class='line'><span class="n">string_value</span> <span class="o">=</span> <span class="s2">&quot;&quot;</span>
</span><span class='line'>
</span><span class='line'><span class="k">def</span> <span class="nf">add_to_string</span><span class="p">(</span> <span class="n">line</span> <span class="p">)</span>
</span><span class='line'>  <span class="n">mutex</span><span class="o">.</span><span class="n">synchronize</span> <span class="k">do</span>
</span><span class='line'>    <span class="n">string_value</span> <span class="o">+=</span> <span class="n">line</span>
</span><span class='line'>    <span class="n">string_value</span> <span class="o">+=</span> <span class="s2">&quot;</span><span class="se">\n</span><span class="s2">&quot;</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'><span class="k">end</span>
</span><span class='line'>
</span><span class='line'><span class="n">thread1</span> <span class="o">=</span> <span class="no">Thread</span><span class="o">.</span><span class="n">new</span><span class="p">{</span> <span class="n">add_to_string</span><span class="p">(</span> <span class="s1">&#39;line1&#39;</span> <span class="p">)</span> <span class="p">}</span>
</span><span class='line'><span class="n">thread2</span> <span class="o">=</span> <span class="no">Thread</span><span class="o">.</span><span class="n">new</span><span class="p">{</span> <span class="n">add_to_string</span><span class="p">(</span> <span class="s1">&#39;line2&#39;</span> <span class="p">)</span> <span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="n">thread1</span><span class="o">.</span><span class="n">join</span>
</span><span class='line'><span class="n">thread2</span><span class="o">.</span><span class="n">join</span>
</span><span class='line'>
</span><span class='line'><span class="nb">puts</span> <span class="n">string_value</span> <span class="c1"># &quot;line1\nline2\n&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>This method is clearly thread safe, but it no longer is reentrant.  When <code>thread2</code> decides to jump in and run <code>add_to_string</code>,
it can&rsquo;t since <code>thread1</code> holds a lock.  It must wait until <code>thread1</code> is complete before running.  It cannot reenter the method.
Instead, we can just pass in all state, including <code>string_value</code> to overcome this.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="k">def</span> <span class="nf">add_to_string</span><span class="p">(</span> <span class="n">original</span><span class="p">,</span> <span class="n">line</span> <span class="p">)</span>
</span><span class='line'>  <span class="n">original</span> <span class="o">+=</span> <span class="n">line</span>
</span><span class='line'>  <span class="n">original</span> <span class="o">+=</span> <span class="s2">&quot;</span><span class="se">\n</span><span class="s2">&quot;</span>
</span><span class='line'>
</span><span class='line'>  <span class="n">original</span>
</span><span class='line'><span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>This way the method is not only thread safe, but also reentrant.  It does not rely on any outside scope to execute.  The
method can be stopped in the middle of execution and recalled on a different thread without side effects.</p>

<h2>The function should not have any side effects</h2>

<p>Speaking of side effects, that is probably the most important aspect of idempotence.  The method should not have any side effects.
What this means is that every piece of data outside of the method should remain pristine when running a method.  It cannot change
any values outside of its own scope or make any changes in the operating system.  Forget when you learned what
a function was in computer science and go back to your algebra days.  If your algebra teacher showed you the function <code>x = x + 1</code>, you
would have told her she was crazy since this doesn&rsquo;t make any sense.</p>

<p>When it comes down to idempotent methods, this also remains true.  A function in algebra is denoted as <code>f(x) = ...</code>.  It takes in one
or more inputs and returns a result from just those inputs.  Think about your code in the same way.  If I passed in values to your
function, I expect calculations to be done only on those values.  It shouldn&rsquo;t change the global variable, <code>num_calls</code>.  It shouldn&rsquo;t
create any files.  It shouldn&rsquo;t change the state of any value outside of the function.  When I call your function, I expect nothing to
change.  I only expect a return value.</p>

<p>Now, to play devil&rsquo;s advocate, there is always some side effect of calling a method.  That side effect is the time taken to execute
the code.  Most of the time, this can be safely ignored.  There is always an opportunity cost to running code, so we can&rsquo;t change
that even if we wanted to.</p>

<h2>More Information</h2>

<p>I&rsquo;ve talked previously about idempotence.  If you want to learn more about the &ldquo;why&rdquo; of idempotent functions, please check
out the following articles and expect some further discussions in the future.</p>

<ul>
<li><a href="http://www.codefixes.com/2010/11/think-functional-immutable-types-and-idempotence/">Think Functional: Immutable Types and Idempotence</a></li>
<li><a href="http://www.codefixes.com/2010/11/think-functional-lambdas-and-linq/">Think Functional: Lambdas and LINQ</a></li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Ludicrous Speed: Sockets]]></title>
    <link href="http://www.codefixes.com/2012/02/ludicrous-speed-sockets/"/>
    <updated>2012-02-09T08:15:00-06:00</updated>
    <id>http://www.codefixes.com/2012/02/ludicrous-speed-sockets</id>
    <content type="html"><![CDATA[<p>With the popularity boom of internet and intranet based software solutions, and the push for more
<a href="http://en.wikipedia.org/wiki/Service-oriented_architecture">Service Oriented Architecture (SOA) systems</a>, network software usage is at an all time high.  Of
course, many of the systems created are built upon highly abstracted frameworks, so they don&rsquo;t
have to worry much about sockets.  However, there is a high demand for working on those
frameworks and internal networking software that requires a deep knowledge of network systems and
pushing the speed limits on the same hardware.</p>

<p>In a previous life, I worked on high speed trading software where our traders worried about
millisecond delays.  We pushed and received so much data that a standard <a href="http://en.wikipedia.org/wiki/Transmission_Control_Protocol">TCP</a>/<a href="http://en.wikipedia.org/wiki/User_Datagram_Protocol">UDP</a> system could not
come close to keeping up, even on multicore machines with gigabit connections.  What this describes
is a post-mortem of my learning process.</p>

<!-- more -->


<p>One of the downsides of the huge popularity in networking is that at a certain point, the hardware
and firmware guys took away our control.  Most of the network stack is done directly on the network
hardware with the help of the device drivers running in kernel space of the operating system.  This gives
the benefit of &ldquo;hardware acceleration&rdquo; at the cost of customizability.  While code can be written to operate
at lower layers than the <a href="http://en.wikipedia.org/wiki/Transport_layer">transport layer</a>, most of the time these will run slower due
to multiple layers of abstraction from the hardware.  We will focus instead on working with what is given.</p>

<p>There are large and expensive packages that try to solve these problems from companies such as
<a href="http://www.tibco.com/">Tibco</a> and <a href="http://www.informatica.com/us/products/messaging/">29West</a>.
From my time working with them, they are worth every penny if you can afford it and you work in
a problem space that requires that level of throughput.  However, for us peons, we have some options that
can help improve our throughput speeds.</p>

<p>Now, I spend all my time giving examples and micro benchmarks of all possible optimizations I&rsquo;m offering,
but what I&rsquo;ve found is that networking is a little bit like black magic.  There are so many variables
involved that determine final output speed that my benchmarks will not match anything you create, even
if we use the same exact algorithms.  Things such as network latency, number of hops, solar flares, the number
of flaps of a butterfly&rsquo;s wings while traveling from tree to tree outside your window; all cause random differences.
Don&rsquo;t focus too much on the numbers involved with network programming, but instead focus on the concepts.</p>

<h2>UDP for speed</h2>

<p>The first thing you learn when trying to do high speed networking is that you should pull out UDP.  This
is an obvious choice due to the fact that there is no overhead of <a href="http://en.wikipedia.org/wiki/Acknowledgement_(data_networks)">acknowledge (ACK) packets</a> that come with
other reliable transport services.  You will find that most real-time games use UDP because it can push
out the raw speed with minimal delay.</p>

<p>This is because UDP packets are about as raw as you can get on standard home and commercial hardware.  There
is no flow control, no delivery confirmations, and no guarantee that the packets even arrive in the same order.</p>

<p>UDP is good for fast, streaming data.  When you care more for fast packet delivery than you do for guaranteeing
that older packets arrive.  You&rsquo;ll commonly find it being used for streaming video since that data has
hard real-time requirements for delivery.  Video codecs normally have error correction built into the
algorithms because they know they <em>will</em> lose packets.</p>

<p>In the trading world, stale price quotes were normally worthless when newer quotes were available.  We streamed
price quotes as UDP datagrams because we only cared about up to date pricing.  We did lose packets, especially
on huge bursts of data, but that was okay in moderation.</p>

<h2>TCP for reliability</h2>

<p>Not all data is so easily ignored, however.  Most data requires guaranteed delivery.  Just think, if you
were browsing your favorite site and small chunks of data were missing from the page and every once in a while
an image was mangled.</p>

<p>TCP gives the client server an agreement on the data.  The data <em>will</em> arrive on the receiver&rsquo;s side,
the data <strong>will</strong> arrive in order, and the data <em>will</em> be correct.  This is great for files, especially
larger ones that require multiple packets to send it in whole.  The receiving software won&rsquo;t need to
worry about those issues and can use the connection to stream data in correct order.  If you need
reliability, you won&rsquo;t find any protocol that beats TCP on protocol availability and data validity.</p>

<p>The price of those guarantees is great, though.  If you need any type of throughput, you will find
yourself lagging.  When I was building a prototype phone for Motorola, we were using a PC to take readings
from multiple sensors on a phone over an 802.11 wireless connection for real-time and post processing.
The data wasn&rsquo;t all that large or fast, but we constantly got lagged responses because TCP would hold us up.
Because we didn&rsquo;t have time to rebuild it for UDP reliably before a demo, I would SSH into the phone
while someone demonstrated it and would reset the socket connection every few minutes while he was holding
it to get it back working reliably.  &ldquo;Ignore the man behind the curtain.&rdquo;</p>

<p>TCP includes a buffer called the &ldquo;<a href="http://en.wikipedia.org/wiki/Sliding_window_protocol">sliding window protocol</a>&rdquo; buffer.  It will hold a certain number of packets in order
on the receiving side so it can send them off to the client software properly.  This buffer is quite small
and can be easily overflowed, especially on an unreliable network connection such as wireless.  When that
happens, the protocol will start throwing away perfectly good packets it receives until it can catch
back up.  This was what was happening on our phone prototype.  While our network monitor showed great
throughput, most of the packets were being thrown away because of one single missing or bad packet.  We also
lost throughput since the flow controller would start backing off on the speed until the PC could keep up.</p>

<h2>Join the two sides</h2>

<p>We have these two two popular protocols that seem to be mutually exclusive.  Nothing can be further from
the truth.  Instead, you should join forces and use both protocols, just on separate connections.  Have
your stream of unreliable data on one UDP connection and the rest of your data on TCP connections.</p>

<p>Operating systems and network hardware have built in mechanism, called &ldquo;<a href="http://en.wikipedia.org/wiki/Quality_of_service">Quality of Service</a>,&rdquo;
to actually slow down a single connection so one hoggy connection cannot take over an entire network
(although how well this works hugely depends on the quality of their QoS algorithm).  Yes, this is an
over exaggeration of the truth, but it presents the idea simply.  To increase throughput despite QoS
systems, you should increase the number of connections.  On a side note, including multiple TCP
connections also increases the size of your sliding window buffer by a multiple of the number of
connections.</p>

<h2>Threaded service</h2>

<p>This is probably the most important piece, that I question putting it way at the bottom of this article.
When you write a socket program, what do you do with a packet the instance you receive it?  If you said
anything besides buffering it into a queue, you are doing it completely wrong.</p>

<p>The sockets library has an odd system for how you access the receive buffer.  Instead of receiving a
notice that a packet is available to grab, we are notified that the receive (Rx) buffer is ready to be
read, and only if we specifically ask to be notified for the next available stream of bytes.  What this
means is the data will stay within the network buffer until you go and read it.  And while you are reading
from the socket, you could be (and will be, at a certain throughput) losing data.</p>

<p>To minimize this data loss, you need to take the data off the network stream, put it directly on your
internal packet queue, and enqueue another asynchronous (or threaded synchronous) read.  Don&rsquo;t try to parse
the data.  Don&rsquo;t try to analyze what packet you just received.  Don&rsquo;t even create a byte array to host the new
packet.  Just pull the packet and put it in your queue.  Many asynchronous socket libraries (such as <a href="http://www.boost.org/doc/libs/1_48_0/doc/html/boost_asio.html">ASIO</a>)
require a buffer to place the data within, so make sure you have those packet buffers already created.  Use
a memory pool of byte arrays if needed.  Reuse these buffers as much as you can.</p>

<p>The quicker you get to the next read statement, the less likely you will lose packets.  Although I would
love to see multiple queued up reads available from the socket library (you can do this over USB, for
example.  I once queued up 10,000 reads simultaneously over USB to max our throughput.), it doesn&rsquo;t yet
seem available.</p>

<p>Even if you use a non-blocking library such as <a href="http://en.wikipedia.org/wiki/Input/output_completion_port">I/O Completion Ports (IOCPs)</a>, you need to follow these same rules
because the same results will occur.  At the trading firm, we would normally lose packets when using
IOCPs because we had the same thread reading from the socket along with parsing them out.  Non blocking APIs
still have to follow the same rules we do, so don&rsquo;t expect that using one will allow you to ignore these issues.</p>

<p>Oh, and by all means, never use the UI thread to do any networking.  You&rsquo;ll find that just drawing to the display
can cause networking problems due to the delays.</p>

<h2>TLDR: Too long. Didn&rsquo;t Read</h2>

<ul>
<li>Use UDP when you can get away with lost packets, but need the speed.</li>
<li>Use TCP when you need guaranteed data.</li>
<li>Use a combination of the two on multiple connections when you need both.</li>
<li>Use more than one connection to maximize throughput.</li>
<li>Don&rsquo;t do anything other than read from the socket on the receiver thread.</li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Becoming Great]]></title>
    <link href="http://www.codefixes.com/2012/01/becoming-great/"/>
    <updated>2012-01-17T16:31:00-06:00</updated>
    <id>http://www.codefixes.com/2012/01/becoming-great</id>
    <content type="html"><![CDATA[<p>As software developers or engineers, we are constantly on the prowl to improve our development and design skills.
There are thousands of books, countless blogs, and over 1400 languages (based on the results seen at
<a href="http://99-bottles-of-beer.net/">99 Bottles of Beer</a>).  There are only 24 hours in a day and most of it is spent
working, sleeping, commuting; just living our lives.  Who really has the time to keep up with how quickly technology
is moving?  It&rsquo;s just not humanly possible.  We have to stop trying to become experts and start becoming <em>good enough</em>.
This is when we will truly become great.</p>

<!-- more -->


<p>This goes against everything I was taught growing up.  I was always told that to be the best, you had to force yourself
to become that expert.  The problem lies in that technology has advanced to such a degree that it&rsquo;s not possible to
become that expert in a short enough time period to even stay relevant.  No time in history has there ever been such
a growth in a field that one could obsolete him or herself so quickly just by trying to learn everything there
is to know about their profession.</p>

<p>Take programming methodologies as an example.  If you know assembly, you will know that there is no such thing as a loop.
Sure, you have things such as JNZ (Jump if Not Zero) or any of the other conditional jump statements, but those are just
gotos with a condition attached to them.  This was and is still common when you jump down to most byte code.  For and
while loops just don&rsquo;t exist in these contexts.  All of a sudden, with an influx of procedural languages, and with an
article written by Edsger W. Dijkstra named
<a href="http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html">Go To Statement Considered Harmful</a>,
this was bad practice and programmers had to adapt by using loops, method calls, etc.</p>

<p>The same happened with object oriented programming, following procedural.  The use of functions alone was deemed bad
practice, so most of us moved on to thinking in objects, interfaces, and methods.  It&rsquo;s happening again today with
functional languages such as Erlang and Haskell.  Again, object oriented programming is considered harmful because
it has too many side effects.  So, some people are moving on.  This is not going to stop any time soon.  The explosion
in computing power has had the effect of exploding the lines of code required based on what users expect in their
software.  New methodologies have to be created to mitigate some of these issues as they arise.</p>

<p>This doesn&rsquo;t even go into the vast number of programming languages in production today.  Take in all the legacy code
still written in languages such as Cobol and add in languages such as Ruby, C++, Python, etc.  Then you add in the
managed languages such as those written for the .NET framework and the Java Runtime Environment (JRE).  Finally add in
some of the newly popular languages such as Erlang and Haskell.  What you get is the impossible task for any person
to keep up with the technology.</p>

<h1>So How Do I Keep Up?</h1>

<p>This is an interesting dilemma.  On one hand, I spent the first part of this post explaining that you can&rsquo;t keep up,
but now I&rsquo;m going to explain how you can.  I consider myself lucky.  I&rsquo;ve had the opportunity to work in a huge range
of industries on a large number of languages.  In college, I was a C++ guy.  Growing up, I spent years honing my
skills in its idiosyncrasies.  And then, when I graduated and need a job, I took on C#.  My next job went back to C++
but mixed in some Perl and Python, I then went back to a mix of C++ and C#.  Finally, I switched completely over to
Ruby and Rails.  This makes me fairly marketable since I can confidently apply for a job in C++, C#, Ruby, Python,
or Perl.  Being marketable should be high on anyone&rsquo;s priorities due to the state of the job market in a whole
(recession) and the job market for programmers (booming).</p>

<p>Now I&rsquo;ll tell you what I&rsquo;m not.  I don&rsquo;t have any certifications.  I&rsquo;ve never been comfortable enough with a
language to contribute to their core library.  I don&rsquo;t know exactly how the garbage collectors work in .NET or
Java.  There are a lot of things I just don&rsquo;t know about the languages I work in daily, the small details about
a language that are not required to be known to write great code within its confines.</p>

<p>Even though I can&rsquo;t call myself an expert at any of these languages, I can say that I&rsquo;m a jack of all trades.  I
decided early in my career that I would not focus solely on one language because they can go out of popularity
multiple times in my lifetime.  I&rsquo;ve shown instead that I can adapt to change in infrastructures.</p>

<p>It&rsquo;s not a difficult task.  On the contrary, it&rsquo;s quite easy.  Instead of continuing to read the same blogs on only
Ruby, branch out and start reading about .NET or Java.  Get a better understanding of what the alternatives are,
and maybe one day you&rsquo;ll find that the language you know and love just may not be the perfect solution for your
next project.</p>

<h1>Master of None</h1>

<p>When people say &ldquo;Jack of all trades,&rdquo; we all know the next line to that statement is &ldquo;master of none.&rdquo;  This can be
worrisome to quite a few people because they believe that will hinder their career growth.  If you look at job
descriptions for senior level developers, you&rsquo;ll see things such as &ldquo;requires 5+ years developing in X,&rdquo; or &ldquo;looking
for an expert in Y.&rdquo;  If you looked at my resume, that would have made me unqualified at my current job because
I never had written a line of production ruby code in my life before it.  On the coding test, I had to look up
half of the ruby methods because they weren&rsquo;t ingrained into my brain yet.  Of course, I did get the job
despite these shortcomings due to my broad knowledge of programming.</p>

<p>Theres another side effect of broadening your knowledge.  You will get a different perspective on the problems
you encounter in your job.  Learning functional programming will teach you how to handle threaded applications
simpler in C# or Java.  Learning a static language will give you a better understanding of what strict types
gives you in Ruby.  You will be able to know when it&rsquo;s best to use TCP to send messages to another process and
when it&rsquo;s better to use a message queue.</p>

<p>While you may not know exactly how to install and instantiate the message queue, you will find it much easier
to learn how to do it.  You have been practicing learning new tools, so you will be able to pick up basics of
setting up <a href="http://www.rabbitmq.com/">RabbitMQ</a> knowing right away that it uses Erlang&rsquo;s cookie system for security.
Once you break free of trying to become an expert will you finally start becoming great.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[2012 - End of the (tech bubble) World?]]></title>
    <link href="http://www.codefixes.com/2012/01/tech-bubble/"/>
    <updated>2012-01-05T21:00:00-06:00</updated>
    <id>http://www.codefixes.com/2012/01/tech-bubble</id>
    <content type="html"><![CDATA[<p><img class="right" src="http://www.codefixes.com/images/blog/greed.jpg" title="&#34;Greed&#34;" alt="&#34;Greed&#34;"></p>

<p>Startups are everywhere.  They are the hot ticket item.  Get millions of people to join your website, and you are a rich man.  I&rsquo;m not deeply tied in with the startup community, but I personally know a few people doing startups, and I can see flaws in their business model.  Still, the market has shown recently that they will still &ldquo;violently fund&rdquo; these startups without any plans for profits.  All this sounds too familiar.</p>

<!--more-->


<h4>Disclaimer:</h4>

<p>I apologize in advance since this is veering far from my expertise and diving into the business world.  I am by no means qualified to make such broad, sweeping statements about the web industry.  Sometimes, I just like to rant.  Also, notice the question mark in the title?  Consider me Fox News.  I&rsquo;m just asking questions.</p>

<h2>Seed Money Business Plan</h2>

<p>Software prototyping tools are prevalent.  The days past of creating prototypes in C++, creating thousands of lines of code just to throw them away are gone.  Web developers can use Rails, Django, CakePHP, or ASP.NET MVC (depending on your language preference) to create simple examples of their idea.</p>

<p>So what do some of these companies start with?  Trying to find seed money.  In general seed money can be great for a startup.  It&rsquo;s good when you can play with &ldquo;Other People&rsquo;s Money (OPM).&rdquo;  But, creating web applications can be done so cheaply that you wonder why these people spend months trying to find money to fund their development when they could have used that time to create the product in the first place.</p>

<p>Businesses always require a solid business plan, so I don&rsquo;t expect startups to give up on the idea of creating one.  However, a solid prototype or production application can sometimes sell itself.  If it can&rsquo;t, the business plan should write itself once you put some code to work.  Trying out your product can quickly show you flaws in your business plan and even more or better ways to make money.</p>

<p>Many of the people I&rsquo;ve talked to about seed money see it as the way to personal profitability and lack any real plans of future profits for the company.</p>

<h2>Crowd Sourcing</h2>

<p>The idea is solid enough.  Build it, and they will come.  If you&rsquo;re trying to make another social networking site, let me stop you here.  If you build it, it will sit idle.  You have a catch-22 here.  People drive content, but you can&rsquo;t intice those people until you have that content.  So, if your business plan requires your content to be created by others, you have to find a different way of bringing in these users.</p>

<p>Now, think about your business plan.  Do you have a good way of bringing in these users without Tweeting, FaceBooking, or whatever the verb format of Google Plus is?  If you don&rsquo;t, your idea is probably doomed to failure.  Go back, look at a different way of generating content or bringing in those users.</p>

<p>The internet is full of users that could be described as having Attention Deficit Disorder (ADD).  And, because of how easy it is to create simple web applications even for non professional programmers, there are tons of social sites available.  You have to find a way of not only bringing that user to your site for the first time, but also keep their attention long enough for them to care about coming back.</p>

<h2>Growth Opportunity</h2>

<p>There are a ton of web startups out on the internet.  The chance of getting a new user to commit to your site without them jumping from another site is probably pretty slim.  This could be good news for you because that would allow that person to use your site that much more.  The reason that person would jump from the older site is that it no longer fulfills their needs.</p>

<p>And this is the heart of the problem.  Popularity will always be cyclical.  You need to grow your business horizontally, not just vertically.  What this means is you need to move into other opportunities before your business popularity drops.  Web companies seem to be so focused on a niche market that it&rsquo;s very difficult to expand.  Many of these companies wind up dying out instead of moving on.</p>

<h2>IPO</h2>

<p>So if a company is doomed to die out if they don&rsquo;t expand horizontally, what is their ultimate goal?  From what I can gather, it&rsquo;s the infamous initial public offering (IPO) or the sell.  This is overly prevalent recently with the IPOs of LinkedIn and Groupon.</p>

<p>I&rsquo;m going to use Groupon as the example here since it&rsquo;s the epitome of my points.  When they had their IPO on November 4th, 2011, they raised $700 million, valuing them at close to $13 billion.  And this is for a company that loses $100 million a quarter.  The founders and early investors got filthy rich off of this business that has no chance of making money, and the late investors are stuck holding the bill.  When things looked dim for the Groupon company, when their capital was running out, they rushed the IPO to make sure they weren&rsquo;t the ones dealing with the bill.</p>

<h2>Another Dot-com Bubble</h2>

<p>It seems a lot of these companies are falling down the same path as the original dot-com bubble.  These companies have very high P/E ratios, bright red balance sheets, and no real future of profitability.  Yet money is still grossly injected into these startups.  There are ways of making web companies profitable, and I hope to see more of it.</p>

<p>For those companies that are already over invested?  My only question: who will be the ones holding the toxic assets in the end?</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[My Must Have Gems]]></title>
    <link href="http://www.codefixes.com/2011/10/my-must-have-gems/"/>
    <updated>2011-10-11T21:10:00-05:00</updated>
    <id>http://www.codefixes.com/2011/10/my-must-have-gems</id>
    <content type="html"><![CDATA[<p><img class="right" src="http://www.codefixes.com/images/blog/ruby-gem.png" title="&#34;Ruby Gems&#34;" alt="&#34;Ruby Gems&#34;"></p>

<p>When you create a new rails project, there are a few gems that you require to even get started. While rails does have a lot built into itself to help start you off in creating  great applications, I find myself in need of a more complete starting point.  I&rsquo;ve compiled a short list of my most commonly used gems in new rails projects.</p>

<!--more-->


<h2><a href="https://github.com/plataformatec/devise">Devise</a> &ndash; Authentication</h2>

<p>Every one of my projects in rails has required some sort of authentication system.  I have not found a better solution than Devise. It seems like it&rsquo;s the de-facto standard for authentication in rails. Even if you want to use other external authentication systems, like Facebook or Twitter, there are plugins built for devise that handle these systems also.  It&rsquo;s a super simple installation process and even simpler to use.</p>

<h2><a href="http://rspec.info/">RSpec</a> &ndash; Testing</h2>

<p>This is just a personal preference.  Test::Unit or Minitest can be substituted for rspec, but I&rsquo;ve gotten used to the DSL that rspec includes.  Plus I prefer its included mocking framework for those few times that I need to stub out a method call.</p>

<h2><a href="https://github.com/thoughtbot/factory_girl">factory_girl</a> &ndash; Test factories</h2>

<p>While rspec does give me a full featured mocking/stubbing framework, I personally prefer to use real objects for tests.  However, building objects using standard ruby methodologies can be time consuming and verbose, especially when you have hierarchical models. Factory girl simplifies this with a small DSL that allows me to define model factories one time while still allowing me to change them per test.</p>

<p>The standard still used in rails is to use fixtures, but I feel that fixtures takes away part of the meaning of the test since it is separated in a different file.  Plus you have to know what exists in the fixtures before hand to make sure your tests are valid.  Instead, I can start with a clean slate for every test and define the model instances as they are needed, and define the exact parameters that are needed for that test instance.</p>

<h2><a href="https://github.com/guard/guard">Guard</a> &ndash; Automation</h2>

<p>While not the first automated testing system, it is my favorite.  Using its plugin architecture, I can have it tests for files that have just been updated, start up my spork server, and restart pow as needed.</p>

<p>I also install gems to allow guard to notify me using Growl whenever events occur.  This is probably the nicest feature of guard which allows me to keep my eyes on the code without having to flip to the terminal all the time to run my tests.  That plus the speed of spork allow me to breeze through the code in no time.</p>

<h2><a href="https://github.com/pry/pry">Pry</a> &ndash; REPL and Debugger</h2>

<p>If you are running ruby 1.8.7 or newer and haven&rsquo;t tried pry, you are really missing out on a great REPL system and debugger. On top of the standard read, execute, print loop, it allows you to also use ls and cd to browse through objects.  I use this to replace IRB in all my new rails projects and I&rsquo;ve never been happier.  Ryan Bates has a great screencast on <a href="http://railscasts.com/episodes/280-pry-with-rails">RailsCasts</a> about how to set this up.</p>

<h2><a href="http://haml-lang.com/">Haml</a> &ndash; Template Engine</h2>

<p>When it comes to view engines, you have a few to choose from.  Rails comes standard with erb, but I prefer to use Haml. While some people may not like the limitations that come with Haml, I find the single line definitions force me to simplify my views significantly. I also like the simple syntax and the conciseness to the template language.  After working with HTML and XML for so long, it&rsquo;s nice to see how little code is required to do the same thing.</p>

<p>Of course, Haml does use indentation rules similar to Python and CoffeeScript. This can be a major turn off to some users. If you keep your views simple and extract partials wherever it seems reasonable, the indentation shouldn&rsquo;t be more than three or four layers deep.</p>

<h2><a href="https://github.com/jnicklas/capybara">Capybara</a></h2>

<p>Regression and full stack testing can be difficult without the right tools.  Luckily we have Capybara to handle a lot of the backend work to call into our server.  What we need to code is CSS or XPath selectors like you would using jquery. Add in a few automated input handling through the Capybara gem and you can easily  run through multiple pages in only a handful of lines.  This helps a great deal because it takes a lot of headaches of integration tests, making it more likely that I will write them more often.</p>

<h2>Summary</h2>

<p>As I had <a href="http://www.codefixes.com/2011/10/how-rails-won-me-over/">written before</a>, one of the greatest assets that the rails community has is its vast collection of ruby gems. I have not seen another community release as many of these projects in such a relatively short amount of time.  Take advantage of some of these and you will find that you are much more productive and have fewer errors because you will have to write much less code and use more production tested gems.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A New Face: Octopress and Jekyll]]></title>
    <link href="http://www.codefixes.com/2011/10/a-new-face-octopress-and-jekyll/"/>
    <updated>2011-10-06T16:30:00-05:00</updated>
    <id>http://www.codefixes.com/2011/10/a-new-face-octopress-and-jekyll</id>
    <content type="html"><![CDATA[<p><img class="right" src="http://www.codefixes.com/images/blog/octopress_teaser.png" title="&#34;Octopress&#34;" alt="&#34;Octopress&#34;"></p>

<p>If you&rsquo;ve been reading this site in the past, you may have noticed a face lift.
This isn&rsquo;t just a face lift, but a complete rewrite of the blog software that
I use.  I used to be hosting this site on wordpress, but I found I was battling
the system too often and trying to find work arounds for the quirks.
Now this site is just a bunch of static HTML files that were nicely
generated using <a href="http://octopress.org/">Octopress</a> and <a href="http://jekyllrb.com/">Jekyll</a>. This
should significantly improve the speed of the site and allow me to write
more often (with more code examples).  I&rsquo;m also finally able to host on &ldquo;the cloud&rdquo;
using <a href="http://aws.amazon.com/s3/">Amazon&rsquo;s S3</a> service which
finally allows me to do automated deployments.  As an added bonus, it also
increases my geek status.</p>

<!--more-->


<p>So what real benefit does this give me?  Well for one, I can write everything
offline in markdown format without worrying about some converter messing up
the formatting.  I also have more control over the styling and layouts of the
page and it greatly simplifies my setup.</p>

<h2>Markdown and SASS goodness</h2>

<p>Creating posts using only HTML tags can be time consuming and error prone.  The
problem is you have to force yourself to a subset of HTML which may be removed
by the Wordpress editor anyway.  Instead I can now use
<a href="http://daringfireball.net/projects/markdown/">markdown</a>, which is a
simplified markup language that can be converted for me automatically and safely.
I can also use <a href="http://sass-lang.com/">SASS</a> to drastically simplify my CSS code.</p>

<p>Markdown, at least with the extensions brought in from Jekyll, has the benefit
of allowing me to insert code directly into the content.  I&rsquo;ve struggled getting
code to properly format using Wordpress in the past, so this is a huge benefit.</p>

<h2>Uses ruby</h2>

<p>As a new found ruby developer, I like the fact that Jekyll allows me to run
arbitrary ruby code while generating the site.  For example, I use this to insert
the page links in the index pages.  I don&rsquo;t have to manually handle these
housekeeping issues by handing them off to an automated process.  The fact that
it&rsquo;s ruby is a bonus since this is what I work with daily.</p>

<h2>No back-end</h2>

<p>The best part is that the Markdown is converted to static HTML files.  That&rsquo;s right,
there&rsquo;s absolutely no back-end for this site now.  You&rsquo;re downloading HTML files I
generated on my computer directly without worry about putting things properly in
databases.  That means I can&rsquo;t have downtime due to a database crash, and there&rsquo;s
no way I can lose data due to database corruption.  No need to run multiple servers
to handle the separation.</p>

<p>It&rsquo;s also much more difficult to attack the site.  The only point of attack is now the web
server which will always exist.  There&rsquo;s no need to worry about patching wordpress
anymore (which is still an ongoing battle) nor any other software.  I just let Amazon
worry about the server software and just worry about content.</p>

<h2>Automatic deployment</h2>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'><span class="nv">$ </span>rake s3deploy
</span></code></pre></td></tr></table></div></figure>


<p>That&rsquo;s all I have to do to push the new content live.  It&rsquo;s a great feeling.</p>

<h3>Offline access</h3>

<p>One of the issues I ran into a lot was that my wordpress site could not be accessed
without an internet connection.  I spend a lot of time on the train to and from work
where I don&rsquo;t have access to the internet.  That means I could not see what the site
would look like while making changes during that time.  I&rsquo;m sure I could have setup
a LAMP server locally to do development, but it was more work than I wanted to put into
it.</p>

<p>Instead, I can run the entire site locally by generating the site or running a rake
task to run a <a href="http://en.wikipedia.org/wiki/WEBrick">WEBrick</a> server.  And, it will look
and at exactly as I see it when I finally do deploy.  There are a few external
services that won&rsquo;t work, such as my twitter feed, but that&rsquo;s a minor issue
since I don&rsquo;t usually maintain that part of my site.</p>

<h2>Version control that makes sense</h2>

<p>As a software developer, I&rsquo;m used to great version control systems that give me more
than just history.  I&rsquo;m now storing the entire site in a github project.  Since
markdown files are just files, I can do diffs, branches, merges, even cherry pickings.
You can&rsquo;t even start to think about doing these things in wordpress, especially without
some major modifications to the software.</p>

<p>If you&rsquo;re interested in my setup, you can go to my
<a href="https://github.com/markglenn/codefixes.com">github repository</a> and download the
entire thing onto your computer.  In the future, I may talk about how I set the site
up and my own customizations.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Why I chose Rails over MVC]]></title>
    <link href="http://www.codefixes.com/2011/10/how-rails-won-me-over/"/>
    <updated>2011-10-03T00:00:00-05:00</updated>
    <id>http://www.codefixes.com/2011/10/how-rails-won-me-over</id>
    <content type="html"><![CDATA[<p><img class="right" src="http://www.codefixes.com/images/blog/ruby_on_rails_logo.jpg" title="'Ruby on Rails'" >
As a C++ and .NET developer for most of my career, some people found it odd
that I would switch up and jump on the <a href="http://rubyonrails.org/">Ruby on Rails</a>
bandwagon this late in the game.  I had fallen in love with
<a href="http://www.asp.net/mvc">ASP.NET MVC</a> because the true simplicity of its web
development, and while I found some of the quirks of Ruby and Rails initially
annoying, I&rsquo;m now a true believer in Rails and what it can do.</p>

<!--more-->


<p>You&rsquo;re probably thinking that this is just another post of how great rails is
and how you should come over to our side because we have cookies.  I&rsquo;m trying
to write this as an objective view of Rails from a .NET developer&rsquo;s
perspective, so hopefully this won&rsquo;t come off as fanboyism speak.</p>

<p><img class="left" src="http://www.codefixes.com/images/blog/asp_dotnet_mvc_logo.jpg" title="'ASP.NET MVC" >
I have been writing code in C# since v1.1 and the language itself has come into
being my personal favorite of the many I&rsquo;ve used in the past.  It has near
native speed, fast compilation, and a fairly straight forward syntax.  But it
also includes a vast framework which now includes ASP.NET MVC.  Although
ASP.NET MVC isn&rsquo;t the first MVC framework, even for .NET, it&rsquo;s tooling support
in Visual Studio and simplicity has made it the fastest growing in the .NET
world.</p>

<p>Ruby on Rails on the other hand is fairly new to me.  I&rsquo;ve been coding in it
for about a year between versions 2.1 and now 3.1.  While it&rsquo;s new to me, I&rsquo;ve
found myself building web applications quicker and cleaner with it.</p>

<h2>Works in Notepad</h2>

<p>I use notepad as an example here although I use vim.  What I&rsquo;m really saying
here is the framework is easy enough that you don&rsquo;t need an IDE, IntelliSense,
or even documentation up if you are familiar with the framework.  This is not
so true with ASP.NET MVC due to the complexity of the .NET framework and the
amount of generated code.</p>

<h2>Quick Dev Time</h2>

<p>My time is so precious, I didn&rsquo;t even have enough time to write &ldquo;development&rdquo;
in the header.  Okay, so that&rsquo;s not true at all, but I&rsquo;ve noticed Rails to be
quicker in development even though I&rsquo;m an average ruby programmer and pretty
fluent in C#.  This mostly comes down to the simplicity of the framework and
the minimal amount of physical typing that&rsquo;s required.</p>

<p>ASP.NET MVC has improved greatly to reduce the amount of code that&rsquo;s required
to build an application, but it still has a way to go.  Ruby may have the
advantage here because it&rsquo;s a dynamic language and simpler to add duck typing.
While .NET supports multiple dynamic languages, it still has to limit itself to
the lowest common denominator with static objects with some dynamic thrown in.</p>

<p>Also, while ASP.NET MVC 2 and 3 are pushing hard for the user to run with
ADO.NET Entity Framework, it still doesn&rsquo;t make a default choice for the
developer.  While this shows the framework is open to choice, it makes initial
development one step more difficult.</p>

<h2>Gems</h2>

<p>If there was one thing that should make anyone look another time at Ruby on
Rails, it&rsquo;s the huge number of ruby gems available.  Microsoft has had a good
push lately with their NuGet packages and the market has seen a quick explosion
of popularity, but it&rsquo;s still hard to browse for packages unless you know them
before hand.  Mostly this is because there seems to be less discussions on
popular NuGet packages on the Internet.  I&rsquo;m hoping that the tooling in Visual
Studio 11 fixes some of that and people talk more about their favorite NuGet
packages.</p>

<p>On the other hand, I know that in a new Rails application, I&rsquo;m going to pull in
<a href="https://github.com/plataformatec/devise">Devise</a> (authentication),
<a href="https://github.com/ryanb/cancan">CanCan</a> (authorization),
<a href="link:http://haml-lang.com/">Haml</a> (view renderer),
<a href="link:http://rspec.info/">RSpec</a> (testing), and
<a href="link:https://github.com/mislav/will_paginate">Will Paginate</a> (pagination).  With
these, I&rsquo;ve gotten at least a weeks worth of work, if not more, compared to
having to build some of those by hand in ASP.NET MVC.  It&rsquo;s a nice feeling to
know you won&rsquo;t have to write yet another pagination partial.</p>

<h2>Tools</h2>

<p>Okay, this one I know is going to be widely controversial.  Visual Studio is by
far the best IDE built.  Period.  End of story.  If you use even 10% of the
features it has, you will have to agree with me.  However, I now work almost
exclusively with Macs and Linux machines.  This means I cannot use visual
studio.</p>

<p>We have a pretty good alternative with MonoDevelop which I use quite often now,
but the tooling for MVC within it is mediocre at best and only really supports
V1 and some parts of V2 of the MVC framework.</p>

<p>The Rails community follows more along the lines of the Linux and Unix
mentality of having tools do one thing and do them well.  With the fact that
everything runs separately, I can have a script run things automatically for
me.  This is exactly what I do with <a href="https://github.com/guard/guard">Guard</a>
which runs my unit tests automatically every time I save.  It also alerts me on
success or failure using <a href="http://growl.info/">Growl</a> so I don&rsquo;t have to
interrupt what I&rsquo;m doing.</p>

<h2>ASP.NET MVC Not a Bad Choice</h2>

<p>If you&rsquo;re a .NET developer, this is not going to change your mind.  ASP.NET MVC
is still a solid choice, especially if you have existing .NET code you need to
interact with.  Microsoft, in a short period of time, has built up a great
framework that competes with Ruby on Rails and
<a href="https://www.djangoproject.com/">Django</a>.  This hopefully opens your mind a
little to the other options that may exist.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Cross Platform .NET]]></title>
    <link href="http://www.codefixes.com/2011/09/cross-platform-net/"/>
    <updated>2011-09-19T00:00:00-05:00</updated>
    <id>http://www.codefixes.com/2011/09/cross-platform-net</id>
    <content type="html"><![CDATA[<p><a href="http://www.mono-project.com/Main_Page"><img class="right" src="http://www.codefixes.com/images/blog/Mono-gorilla-aqua.100px.png"></a>
Working on software that runs on multiple machines can be time consuming, error
prone, and complicated. Not only do each of the three major operating
systems have different style guidelines, but they even have different
standard programming languages. Mac OS X has <a href="http://en.wikipedia.org/wiki/Objective-C">Objective C</a> and
<a href="http://cocoadevcentral.com/">Cocoa</a>, Windows has
<a href="http://en.wikipedia.org/wiki/.NET_Framework">.NET</a> and
<a href="http://msdn.microsoft.com/en-us/library/ms754130.aspx">WPF</a>, and Linux
has C/C++ and <a href="http://www.gtk.org/">GTK+</a> or <a href="http://www.kde.org/">KDE</a>.
No wonder cross platform applications look so out of place. However, as
unlikely as it may seem, .NET may be the best solution to the native
looking cross platform problem.</p>

<!--more-->


<h2>Java, what could have been</h2>

<p>Java was supposed to be the solution to making your applications work
across multiple platforms. While the
&ldquo;<a href="http://en.wikipedia.org/wiki/Write_once,_run_anywhere">write once, run anywhere</a>&rdquo; slogan
is quite accurate, you can easily pick out a java application on every
desktop platform. Java currently uses its own UI framework named Swing.
The problem is that to make sure that applications run properly on all
the platforms, swing does not follow any of the UI standards set by
Windows, Mac OS X, GTK, or KDE. It also does its own software based
drawing of all its widgets. Because of this, Java has gotten a
reputation for being slow and laggy. The language is quite fast, keeping
up with .NET and in a close race with C/C++, but the UI has really held
it back.</p>

<h2>Qt, the C++ solution</h2>

<p>The <a href="http://qt.nokia.com/">Qt framework</a>, by Nokia (previously
Trolltech), is an impressive cross platform C++ framework that tries to
solve some of the same things Java set out to do, but using the tried
and true C++ language. I&rsquo;ve used Qt since somewhere around version 2,
and I&rsquo;ve found that for a C++ developer, Qt is quote an impressive
framework. Nokia has also put together an IDE specifically for Qt which
inclues code completion which has been difficult in the past due to Qt&rsquo;s
precompiler.</p>

<p>Also, Qt is another framework that does its own widget
drawing, but has the added benefit of supporting hardware acceleration.
This makes Qt&rsquo;s widget drawing to be as fast or faster than native
widgets. If you don&rsquo;t use the hardware acceleration for whatever reason,
the Qt &ldquo;trolls&rdquo; have optimized the heck out of their drawing code. They
also have different skins for the different operating systems to make
the widgets look native, however don&rsquo;t expect all widgets to be there or
look 100% the same. All in all, if you know and like C++, Qt may be a
decent solution.</p>

<p>One of the problems with Qt is that it&rsquo;s built on C++.
While I&rsquo;m a C++ fan, the development time for anything is dramatically
increased. C++ is verbose in general because of the header/source files,
sometimes making it feel like you are writing twice the amount of code.
C++ compilers are also slow due to complicated syntax rules and
<a href="http://stackoverflow.com/questions/3634203/why-are-templates-so-slow-to-compile">C++ template generation</a>.
This makes development slow compared to some of the snappier compilers
for other languages. You also have to take into account compiling a
different executable on every platform. Since the executable code is not
run within a virtual machine, it needs to take into account the
differences between platforms itself.</p>

<h2>Mono and .NET</h2>

<p>You wouldn&rsquo;t realize that .NET is a cross platform solution by looking
at Microsoft&rsquo;s website. That&rsquo;s because to Microsoft, .NET is for the
Windows operating system. You have to look to a smaller company,
<a href="http://xamarin.com/">Xamarin</a>, and the
<a href="http://www.mono-project.com/Main_Page">Mono community</a> to find that they have
developed a fairly complete and production ready .NET implementation
over the past seven years. They&rsquo;ve also created a fairly good IDE for
Mono called <a href="http://monodevelop.com/">MonoDevelop</a>.</p>

<p>So why is .NET and
Mono the better solution? Well, you get the power of the .NET framework
of course. Mono currently supports up to .NET 4.0 with some features of
5.0 already working in the trunk. The .NET compilers are also quite fast
during compilation out of the box giving you major speed boosts over
C++. You also get WinForms support out of the box. That will give you
native rendering in Windows with mimicked results on the other operating
systems. Of course, this is only a starting point. Mono supports a
multitude of other UI frameworks including
<a href="http://www.mono-project.com/GtkSharp">Gtk</a> and
<a href="http://www.mono-project.com/MonoMac">Cocoa</a>, giving you true native
drawing in all platforms. There&rsquo;s even
<a href="http://ios.xamarin.com/">MonoTouch</a>,
<a href="http://android.xamarin.com/">Mono for Android</a>, and
<a href="http://create.msdn.com/en-US/">Windows Phone 7</a> frameworks to cover the mobile side.</p>

<p>The one issue you have when you jump to multiple frameworks, though, is
that you require multiple UI projects for the same solution. This will
be the downside of any project that will try to be native on multiple
platforms, no matter what the language. You can start developing using
WinForms and have a workable solution for all platforms. Later when you
want to add true native support, you can add in WPF, MonoMac, and
GtkSharp. At that point, it&rsquo;s up to you which frameworks to support with
no limitations.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Version numbers... Aren't they supposed to mean something?]]></title>
    <link href="http://www.codefixes.com/2011/06/version-numbers-arent-they-supposed-to-mean-something/"/>
    <updated>2011-06-23T00:00:00-05:00</updated>
    <id>http://www.codefixes.com/2011/06/version-numbers-arent-they-supposed-to-mean-something</id>
    <content type="html"><![CDATA[<p><img class="right" src="http://www.codefixes.com/images/blog/google-chrome-version.png" title="'google chrome version'" ></p>

<p>Software that&rsquo;s been out for many years: v0.71. Google Chrome that&rsquo;s
been out for a short time: v12.0. What has happened to version numbers
that meant something? They have become a way of trying to show market
dominance, or a way from hiding from your users. Worse is the software
that is so afraid of version 1.0 that they will increment so slowly that
we don&rsquo;t know if it&rsquo;s worth upgrading. Looking at a version number for a
piece of software no longer tells me anything.</p>

<!--more-->


<p>Many of you will argue that version numbers never had any true meaning.
This may be true for many commercial applications. A large version
number shows that you&rsquo;ve been around for a while, and it&rsquo;s a great way
of deceiving without anyone really noticing. Minor version numbers were
just incrementers no matter how large or small of a change.</p>

<p>I was bitten by this recently at my job. We are still stuck on ruby
1.8.6, however we are looking to upgrade to 1.8.7. One of the great
benefits of ruby and rails is gems and bundler. A gemfile stores the
names and versions of all the required ruby gems in your project. Even
better, you can specify a versioning system for each gem to
automatically update when asked. This is great, if the gems stay with
versioning standards.</p>

<p>However, one gem did not follow any standards and released a maintenance
release that no longer supported ruby 1.8.6. Since we only locked down
our gem to the second decimal point, this came down the pipeline to our
development machines causing all sorts of new errors in our tests.</p>

<p>The response from the developer was &ldquo;I told you 1.8.6 was deprecated.&rdquo;
Yes, but we expect deprecation warnings to affect us on the next fairly
major release. This was a breaking change, however the version number
did not denote this. I wish I had the time to read the release notes of
every gem, but this is just not possible. I made an assumption based on
the version number and was bitten by it. You may say that this is my
fault for allowing the update, and you would be right. It&rsquo;s something
that I will not repeat in the foreseeable future. However, based on my
own Googling of the error message, I obviously wasn&rsquo;t the only person
that ran into this problem.</p>

<h2>Keeping up with the Joneses</h2>

<p>Remember Java 1.2? I do, and it wasn&rsquo;t all that long ago. How about 1.3,
1.4? Do you remember Java 3 or 4, though? No you don&rsquo;t. That&rsquo;s because
they never existed. Java 1.5 was labelled &ldquo;Java 5&rdquo; and Sun (now Oracle)
never looked back. This was back when .NET was version 2.0 already
making Java seem like old news. The name, &ldquo;Java 5&rdquo; sure looks more
appealing against .NET 2.0/3.5/4.0. Sun also did this with Solaris
jumping from v2.x to v8. Marketing material magically removed any
reference to their old versioning scheme.</p>

<p>This is not limited to Sun, however. Winamp jumped from v3 to v5
because, as their marketing states, it was a combination of v2 and v3.
Since v2 + v3 = v5, this is what they decided on. AOL seemed to release
a new major version every few weeks. Netscape skipped versions 5 and 6
to catch up to Internet Explorer. Many times these major version
releases hardly warranted these numbering changes. This is what happens
when marketing is allowed to take over version numbers.</p>

<h2>It will never be truly finished</h2>

<p>This is the exact opposite problem that plagues many open source
projects. Open source projects are afraid of the v1.0 stigma; that the
program needs to be stable. Instead they will release v0.19.37a (okay, a
little facetious). This makes it more difficult to believe that this
software is ready for production, but nonetheless, it is.</p>

<p>As a reborn programmer into the Ruby on Rails realm, I have been shocked
at the number of gems used in production that are no where near v1.0.
It&rsquo;s not that they aren&rsquo;t production ready. On the contrary, many of
these gems are rock solid. It just feel a bit weary when it looks like
the authors don&rsquo;t believe it&rsquo;s v1.0 worthy.</p>

<p>One response to this is that the developers feel that it&rsquo;s never truly
finished. MAME is one to use this excuse going as far as going from
v0.99 to v0.100. What these projects fail to realize is that there is
life after v1.0. There&rsquo;s actually v2.0, v3.0, and so on. Heck there is
an infinite amount of version numbers just waiting to be taken. If
anyone needs some, I have some extra version numbers lying around that
I&rsquo;m willing to give out for free.</p>

<h2>What I believe in</h2>

<p>I&rsquo;m sure it&rsquo;s difficult to listen to someone standing on his soap box
decreeing what people should or should not do with their version number,
especially when there does not seem to a hard and fast rule for version
numbers. Instead, what you should do is read more on version numbers and
what prior, successful projects have done. I just give one way of doing
this that makes sense to me.</p>

<p>I believe in the [major].[minor].[maintenance] versioning system.</p>

<p>Major is for major changes in the software. This can even include enough
changes to warrant a paid upgrade. When I see a major version change, I
expect and understand breaking changes. I also expect new features, not
just bug fixes.</p>

<p>Minor is for minor updates. These may be small feature additions, major
bug fixes, etc. This can include some breaking changes, but fairly
minor. I should be able to look at the release and fix whatever breaks
within a few hours.</p>

<p>Maintenance is for just that, maintenance builds. This should absolutely
not include any breaking changes. It also should not have any new
features. This is just bug fixes. Leave it at that.</p>

<p>Another example of a good versioning scheme is Ubuntu&rsquo;s month.year.point
versioning. I know right off the bat that 11.04 is the latest major
version and that significant changes have occurred since 10.10. Although
this does contradict my version inflation talk above, it is a well known
versioning method for Ubuntu users and very consisten. It&rsquo;s not just
marketing telling developers that we need to skip a few versions to
catch up to our competitors.</p>

<p>Following a standard will always make things easier for your users. It
doesn&rsquo;t have to be the major, minor, maintenance style that I show
above, but stick to a versioning scheme that fits for your project and
users.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Why are you still crashing?]]></title>
    <link href="http://www.codefixes.com/2011/06/why-are-you-still-crashing/"/>
    <updated>2011-06-20T00:00:00-05:00</updated>
    <id>http://www.codefixes.com/2011/06/why-are-you-still-crashing</id>
    <content type="html"><![CDATA[<p><img class="right" src="http://www.codefixes.com/images/blog/error2.jpg" title="&#34;Windows Error&#34;" alt="&#34;Windows Error&#34;">
I know this is going to be a bit of a controversial topic, but this has
come to bite me recently. An application that I recently purchased that
allowed me to access <a href="https://github.com/markglenn">GitHub</a> from my
iPhone now crashes every time I start it up due to GitHub updating their
API. I don&rsquo;t mean it shows an error message, but crashes back to the
home screen. Obviously this is a major annoyance to anyone trying to use
the app as seen by the recent negative reviews it has been receiving. Of
course, the update to fix the bug was sent to Apple within the same day,
but we all know how fast Apple can be with their review process.</p>

<!--more-->


<p>What happened is GitHub changed the string format of dates within their
API. This is obviously what we call a &ldquo;breaking change,&rdquo; and their API
probably should have been versioned to avoid these types of problems.
However, that&rsquo;s not the real issue that I&rsquo;m trying to address. The
problem is the application didn&rsquo;t safe guard how they access the API.
The assumption was that GitHub wouldn&rsquo;t change their API in any way that
would break compatibility. I question why you would assume anything when
it comes to programs.</p>

<h2>Why aren&rsquo;t you handling errors?</h2>

<p>This is the most obvious issue. I remember back a few years back when
writing C/C++ applications for embedded hardware that if we didn&rsquo;t
handle an error, you would get random behavior. We didn&rsquo;t have stack
traces, core dumps, or even printfs (We had a pretty primitive hardware
setup since we were R&amp;D). What we did instead was check every return
value and used interrupt handlers to handle the <em>exceptional</em> cases. In
other words, we used all the tools available to us to make sure we
didn&rsquo;t fail. In embedded systems, we truly had exceptional cases such as
blown parts, power surges, and even dropped prototypes. String parsing
errors are nothing compared to random hardware failures.</p>

<p>One thing that was drilled into my skull over and over again was that
you need to handle every error state. If a method returned a value and
you ignored it, you would be reprimanded. If a function returned a
value, the function&rsquo;s author obviously believed it was important enough
information to include. You need to check it. With C, there were no
exceptions, so an ignored error caused undefined behavior.</p>

<h2>Why are you ignoring your exceptions?</h2>

<p>This is even more important, and arguably easier to handle, with
languages that support exceptions. Instead of checking the return value
of every function call or checking the global error value, you can check
for errors on an entire block. The call stack is unwound to whichever
position you want that can successfully handle the exception.</p>

<p>Heck, even having a catch all handler at the root of your application
that just shows an error message then quit would be better than letting
an exception unwind the entire stack of your application to be handled
by the operating system. Then I would know that an exceptional situation
occurred instead of thinking the program was just poorly coded.</p>

<h2>Why are you still using a non managed language?</h2>

<p>Okay, this one may seem odd and controversial , especially since all my
examples so far are about embedded C and an iPhone application. This
obviously doesn&rsquo;t relate to certain types of programs that require high
performance (games, trading applications, etc.) or that have the
requirement of a certain language (embedded software). For the rest of
the situations, a language should be used that can help write better,
safer code. There really is no reason to still use C/C++ or Objective C
now that there are multiple options.</p>

<p>Yes, Objective C is questionable since Apple puts this requirement on
all Cocoa applications, but
<a href="http://www.mono-project.com/MonoMac">MonoMac</a> and
<a href="http://monotouch.net/">MonoTouch</a> are great solutions which use a .NET
runtime or compiler. MonoTouch does cost money on top of the money you
have to shell out to Apple for the opportunity to write iOS
applications, so your mileage may vary. I also know Adobe has a similar
solution and I wouldn&rsquo;t be surprised if Java had something also.</p>

<p>The real benefit is garbage collection. Why manage your own memory if
you don&rsquo;t have to? Memory management is difficult to handle perfectly,
especially with exceptions. Patterns such as
<a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization">RAII</a>
in C++ and <a href="http://en.wikipedia.org/wiki/Smart_pointer">smart pointers</a>
mitigate these worries, but the language still allows you to shoot
yourself in the foot if you aren&rsquo;t careful with using these. I hear
<a href="http://developer.apple.com/technologies/ios5/">iOS 5</a> is going to get
<a href="http://en.wikipedia.org/wiki/Reference_counting">reference counting</a>
for Objective C, so this may be a moot point in a few months.</p>

<h2>Patches are not a solution</h2>

<p>Sure, patches for the problem are good. We need fixes so we can run your
software, but that is not the end solution. It is only a bandage on an
incomplete design. What you need to add with the fix is error checking
to make sure this never happens again. Don&rsquo;t just fix whatever error
you&rsquo;re getting. Make sure that all possible future errors are handled.</p>

<h2>We are all human</h2>

<p>Now this may come off as a rant, but I know we&rsquo;re all human. I&rsquo;ve
definitely had crashes in programs that I&rsquo;ve written. Errors happen that
sometimes we really can&rsquo;t predict. However, the options listed above
should help mitigate some of the most likely situations. Just remember
that while we are all human, we can still avoid the crash situation.
Error messages, no matter how cryptic, are infinitely better than core
dumps alone.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Grokking Sockets: Data Link Layer]]></title>
    <link href="http://www.codefixes.com/2011/01/grokking-sockets-data-link-layer/"/>
    <updated>2011-01-16T00:00:00-06:00</updated>
    <id>http://www.codefixes.com/2011/01/grokking-sockets-data-link-layer</id>
    <content type="html"><![CDATA[<p>I know I&rsquo;ve scared away a lot of my audience when I started talking
hardware last time. Well, do not fret because we are starting up the
stack with a software (firmware) layer. The data link layer is how we,
the software guys, fix the problems incurred on the hardware. It&rsquo;s the
layer that does the communication from one computer to another; what
actual bits are being sent. It also detects bit errors if for whatever
reasons the data is corrupted. It&rsquo;s an important layer, although easily
forgotten because it&rsquo;s usually handled by your network card. Even though
it&rsquo;s hidden, you need to understand it because it is the final step in
transmission before hardware.</p>

<!--more-->


<p>The <a href="http://en.wikipedia.org/wiki/Data_Link_Layer">data link layer</a> is the first step
in managing the connection between two network adapters on the same LAN.
It really has two main jobs, and in
<a href="http://en.wikipedia.org/wiki/IEEE_802">IEEE 802</a> networks is defined as two
separate sublayers. The first, or lowest of the two, is the
<a href="http://en.wikipedia.org/wiki/Media_Access_Control">Media Access Control</a> (MAC)
sublayer. You may recognize the acronym MAC from the MAC addresses
printed on your network cards. This is the first address used in socket
communications. The MAC address is a globally unique address flashed
onto the network adapter&rsquo;s ROM space. This address is what is added to
each frame that is sent out, and it&rsquo;s what is monitored to see if a
frame needs to be read.</p>

<p>Of course, that&rsquo;s not the only thing it has to
worry about. If we have a group of computers on the same LAN, we would
have interference. Imagine that instead of computers, we have a group of
people sitting at a small table. One person can&rsquo;t just start talking
without listening for silence first. If every person started talking
without listening for silence first, all we would hear is noise. While
some protocols can pick out streams from noise, like picking up a
conversation by the sound of one person&rsquo;s voice, but most of the time
you&rsquo;re stuck with one speaker at a time.</p>

<p>Some of you may have noticed a
problem. If two people are listening and hear silence, they may on
occasion start talking at the same time. In the case of two people, they
will usually hear this and go back and forth saying &ldquo;No, you go first.&rdquo;
In the case of the MAC sublayer, a simpler process of random delays
after a collision occurs. Each network adapter chooses a random wait
delay and then tries again. In the case of another collision, a new
larger random number is chosen. This is called
<a href="http://en.wikipedia.org/wiki/Carrier_sense_multiple_access_with_collision_detection">carrier sense multiple access with collision detection or CSMA/CD</a>.</p>

<p>The MAC sublayer also handles frame synchronization. It determines at
which bit a frame starts and ends. This is done through different
methods and varies based on standards. The usual method is to stuff a
special sequence of bits or bytes at the beginning and end of a frame.
These are known as
<a href="http://en.wikipedia.org/wiki/C0_and_C1_control_codes">start of text (STX) and end of text (ETX)</a> sequences.
So if a receiver notices an ETX sequence at an unusual point, it knows
that the frame has been corrupted.</p>

<p>The other sublayer is the
<a href="http://en.wikipedia.org/wiki/Logical_Link_Control">Logical Link Control</a> (LLC)
sublayer. While the MAC sublayer can detect frame errors of size changes
or missing bits, it alone cannot detect bit errors. For example, if say
the frame is 1500 bytes long, and only one bit has been incorrectly
inverted, the MAC sublayer would never know. In this case, the LLC
sublayer adds the
<a href="http://en.wikipedia.org/wiki/Cyclic_redundancy_check">CRC</a> value of the
frame to the end. This will detect nearly all the bit errors.</p>

<p>The LLC also handles flow control. When a sender sends out a frame, it expects
the receiver to acknowledge its arrival. In simple cases, the sender
would wait for the acknowledge packet before sending the next. This way,
the receiver determines the rate at which packets are sent; how fast the
receiver can receive. Of course, there&rsquo;s a delay using this method known
as a <a href="http://en.wikipedia.org/wiki/Round-trip_delay_time">round trip delay time</a> (RTT). To get
around this, most processes support a
<a href="http://en.wikipedia.org/wiki/Sliding_window_protocol">sliding window protocol</a>. In
simple terms, a sliding window allows for a range of packets to be on
the line waiting for ACK packets. Ideally the window size would allow
enough packets to be sent to cover the RTT. This would ideally make the
transmission continuous.</p>

<p>Next time we&rsquo;ll be discussing the next layer up, the network layer. This is where the fun job of routing occurs and
where software decisions can start to be made.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Grokking Sockets: Physical Layer]]></title>
    <link href="http://www.codefixes.com/2010/11/grokking-sockets-physical-layer/"/>
    <updated>2010-11-27T00:00:00-06:00</updated>
    <id>http://www.codefixes.com/2010/11/grokking-sockets-physical-layer</id>
    <content type="html"><![CDATA[<p>After a short time of thinking, I&rsquo;ve decided to focus on the 7 layers of
the <a href="http://en.wikipedia.org/wiki/OSI_model">OSI model</a>. We will be
building off the knowledge of each layer to see how they all work
together harmoniously and how we can trick them into going just a little
bit faster. I guess that makes this series an eight part series, so it&rsquo;s
going to be one long journey. Of course, this series isn&rsquo;t called &ldquo;Kinda
knowing sockets,&rdquo; or even &ldquo;Mastering sockets.&rdquo; It&rsquo;s called
<a href="http://en.wikipedia.org/wiki/Grok">Grokking</a> sockets. That requires a
deep, xen like understanding of networking. And that includes layer one
of the OSI model, with all of its hardware goodness.</p>

<!--more-->


<p>Yes, if you look
again at the URL for this site, it will still say <em>code</em>fixes.com. Of
course, you can&rsquo;t master the art of software without knowing how what
your write turns into physical changes. In this case, how does the
information from one computer electronically get sent over to another.
This is not black magic (as much as the electrical engineers want us to
believe).</p>

<p>Let&rsquo;s first talk about the physical layer you may be most
familiar with, ethernet. You may see it as 10BASE-T, 100BASE-TX, or
1000BASE-T. These are the standards for communicating over copper wire,
which is what hides inside the ethernet cable. The wires are paired and
twisted together inside the
<a href="http://en.wikipedia.org/wiki/Shielded_cable">shielding</a>. They are
twisted and shielded to avoid <a href="http://en.wikipedia.org/wiki/Electromagnetic_interference">electromagnetic interference</a>.
The trick here is the twisted pairs carry opposite signals, known as
<a href="http://en.wikipedia.org/wiki/Differential_signaling">differential signaling</a>. This
means that if one wire gets interference, the other will too because the
twisted wires coupled together.</p>

<p>The other standard you probably know and
use is 802.11, or really IEEE 802.11. This is the standard for consumer
grade wireless networks and is pretty standardized in the corporate
world. It transmits wireless signals from one wireless adapter to
another using strange modulation acronyms such as
<a href="http://en.wikipedia.org/wiki/Direct-sequence_spread_spectrum">DSSS</a>,
<a href="http://en.wikipedia.org/wiki/Frequency-hopping_spread_spectrum">FHSS</a>,
and
<a href="http://en.wikipedia.org/wiki/Orthogonal_frequency-division_multiplexing">OFDM</a>.
Basically, all of these describe how to use the wireless frequencies
assigned to each standard. The basic idea is that wireless has to deal
with more interference than a physical wire. Think of your radio in your
last car (because maybe you have one of those fancy HD radios now). When
you were far from a radio station, sometimes you heard two stations
switching back and forth within the static. This is what radio
frequency, or RF, interference &ldquo;sounds&rdquo; like.</p>

<p>These radio stations are
given dedicated bands of space by the FCC (in the U.S.). That means they
are guaranteed that band by the government. WiFi does not have that
luxury. Everyone needs to play nice and share the same bands. Worse yet,
the transmission performance is so poor on these bands, that the FCC
didn&rsquo;t want it and has opened it up to anything. That&rsquo;s why we see
2.4GHz cell phones, 2.4GHz wireless keyboards/mice, and 2.4GHz
bluetooth. Everything is on this band and we want to get over 100Mbps to
our PCs.</p>

<p>That&rsquo;s where the complicated spread spectrum type modulations
come into play. At its most basic level, a signal is transmitted on a
coded set of frequencies that is agreed upon by the sender and receiver.
This is called <a href="http://en.wikipedia.org/wiki/Code_division_multiple_access">code division multiple access</a>.
Since the frequencies are coded, another sender can send on a different
code simultaneously. The receiver then takes the full spectrum, and
using advanced math that is above my level, extracts or de-spreads the
original transmission.</p>

<p>There are further ways of handling interference
such as 802.11n&rsquo;s use of
<a href="http://en.wikipedia.org/wiki/Orthogonal_frequency-division_multiplexing">orthogonal frequency-division multiplexing</a>.
It uses multiple signals,
<a href="http://en.wikipedia.org/wiki/Subcarrier">subcarries</a>, and higher level
math than the previous versions. If you&rsquo;re really interested, or just a
glutton for punishment, you can read more about it on Wikipedia.</p>

<p>So what
does this all mean for us coders? Well for one, you can now impress your
engineer friends by using acronyms such as CDMA and complex vocabulary
such as &ldquo;orthogonal subcarries&rdquo;. But in reality, we need to know one
thing out of all of this. Interference is our main source of slowdowns
in layer 1 of the OSI model. So, we have a few options to think about.
If you need the dedicated bandwidth, go with a wired connection. This
will give you some level of guaranteed bandwidth, although there are
some things to worry about higher up the OSI model.</p>

<p>If you have to use
wireless, know that you may lose large chunks of your data. If you&rsquo;re
using TCP, this equates to large lags and drops. You can avoid some
interference by switching channels on your routers and making sure two
routers near each other are on orthogonal frequencies. This will avoid
interference between the routers and minimize the crosstalk between
computers on different routers.</p>

<p>You can also switch bands all together
to the 5GHz band. There will be generally less interference on this band
right now since most consumer grade electronics don&rsquo;t use it. Plus the
added benefit of 802.11n&rsquo;s four simultaneous open channels using
<a href="http://en.wikipedia.org/wiki/Multiple-input_multiple-output">multiple input, multiple output</a> and
its multiple antenna array for allowing directional transmission will
give you much higher performance with much less broadcast noise.</p>

<p>Also,
since 802.11n is an open ended standard in some regards, you will find
that the expensive hardware will actually out perform the cheap stuff.
So, if you need the bandwidth, get ready to pony out a lot more money
for a router that has higher coding rates and more simultaneous streams.
These babies can get up to 600 Mbps (theoretical), if you have the right
hardware.</p>

<p>So now that you know the basics of the first layer of the OSI
Model, we can continue building upon that knowledge to understand the
next article in this series about layer 2, the data link layer.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Grokking Sockets: Overview]]></title>
    <link href="http://www.codefixes.com/2010/11/grokking-sockets-overview/"/>
    <updated>2010-11-23T23:19:56-06:00</updated>
    <id>http://www.codefixes.com/2010/11/grokking-sockets-overview</id>
    <content type="html"><![CDATA[<p>I&rsquo;ve worked with socket programming on and off (mostly on) for a good
ten years. Although this doesn&rsquo;t make me an expert, by far, this has
given me good insight into what seems to work and what doesn&rsquo;t. This
will most likely be a multi-part piece as sockets are a complicated
beast. What I will be talking about is a very low level understanding of
how sockets work and what each of the seven layers of the OSI model mean
to you. Hopefully you will have such a level of understanding of sockets
and protocols that you will <a href="http://en.wikipedia.org/wiki/Grok">grok</a>
them. Only when you reach this level can you understand how to max out
performance.</p>

<!--more-->


<p>As with many of my other posts, we&rsquo;re really here to talk
about maximizing performance. The world has changed with the advancement
of multicore processors and cloud computing. As we move into
distributing our work among multiple processors and machines, these
separate processes will need to communicate. The IP protocol is now
ubiquitous due to the internet&rsquo;s popularity. It continues growing as
processes are moved to the cloud and APIs are moved to RESTful sites.</p>

<p>So the <a href="http://en.wikipedia.org/wiki/OSI_model">Open Systems Interconnection model</a> or OSI model defines the
basis of most networking systems. This includes the full stack that runs
the internet from HTTP down to the 802.3 standard (ethernet cable). I&rsquo;ll
briefly define each of the seven layers and how they map to the web.
Each layer of the stack adds its own unique wrapper upon the packet it
receives from above. In other words, the layers don&rsquo;t care about each
other. They just know they need to add some data to the packet as it
goes down the layers, and reads from the packet as it goes back up on
the other side.</p>

<p><strong>Layer 1 &ndash; Physical Layer</strong></p>

<p>This is the one that&rsquo;s
probably the easiest to understand. This is the standard of actually
sending bits down the wire. This includes your standard ethernet and
wireless standards. This defines not only the signals and voltages, but
also the physical connectors and wires. There&rsquo;s not much for efficiency
that we can do on this layer since it&rsquo;s physical hardware and doesn&rsquo;t
allow for software modifications.</p>

<p><strong>Layer 2 &ndash; Data Link Layer</strong></p>

<p>The data link layer defines the protocol of talking between two machines that are
physically connected. 802.3 extends into this layer describing what each
byte means. This is also where your MAC address comes into play&hellip; you
know, that long hex string written on your network card. Again, this is
usually physical hardware, so not much we can do. If you have an
&ldquo;ethernet&rdquo; card, it will probably only speak ethernet. Flow control and
error checking are done here too.</p>

<p><strong>Layer 3 &ndash; Network layer</strong></p>

<p>Okay, this is where code starts getting thrown in, although mostly in firmware. You
may know this layer as the IP layer in protocols such as TCP/IP and
UDP/IP. The network layer defines how packets are routed from computer
to computer. This is mainly how far up routers and hubs go when it comes
to analyzing packets. They read up to layer 3, then decide the optimal
path this packet should travel.</p>

<p><strong>Layer 4 &ndash; Transport Layer</strong></p>

<p>This is
the basis of how one computer &ldquo;sees&rdquo; the other, even though they are not
directly connected. This is where TCP and UDP live. Decisions on how you
use this layer can affect your throughput and data quality. This is
probably the most important layer to grok to improve your throughput.
TCP is your connection oriented protocol, where the two PCs communicate
as if they were next to each other. UDP is the same, except the
connection state is not shared and the data may come randomly.</p>

<p><strong>Layer 5 &ndash; Session Layer</strong></p>

<p>Layer 5 isn&rsquo;t all that important in the TCP/IP world.
It defines things such as VPNs and broadcasting methods. This is only
useful if you are building something custom. Otherwise, you would
normally just use an off the shelf component for this. Ignore it for
now.</p>

<p><strong>Layer 6 &ndash; Presentation Layer</strong></p>

<p>This is where things become a
little grey. The presentation layer defines how the packets work
together as a whole. That means if you&rsquo;re sending a file over TCP/IP,
while it may break up into packets, this layer will use them all as a
whole. This is straight code. It is normally the code that handles the
raw packets and converts them to useful information in your software.
Security is also added at this layer, so things like SSL live here.</p>

<p><strong>Layer 7 &ndash; Application Layer</strong></p>

<p>This is the bread and butter. This is
what the user actually uses and sees on the screen. After the packets
are pieced together in layer 6, your application must use that
information. This part of the application is usually run on the UI
thread, and normally does not interact with sockets directly.</p>

<p>In future posts, I will go into more detail about each one of the configurable
layers and describe steps that you can do to increase throughput.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Maybe Your API Sucks]]></title>
    <link href="http://www.codefixes.com/2010/11/maybe-your-api-sucks/"/>
    <updated>2010-11-21T00:00:00-06:00</updated>
    <id>http://www.codefixes.com/2010/11/maybe-your-api-sucks</id>
    <content type="html"><![CDATA[<p>This goes back to my love/hate relationship with Ruby on Rails. I&rsquo;m an
enterprise .NET developer by day, but I&rsquo;m trying to be a rails developer
by night. I say trying, not because I don&rsquo;t know rails, but because
their documentation sucks. Sure, there are plenty of tutorials for
beginners, maybe some for intermediate developers. They are spread out
across the internet in a haphazard way. Mostly blog posts showing
something cool they found out by perusing the rails codebase or by word
of mouth. So their documentation sucks, but I believe it&rsquo;s something
deeper. Maybe your API sucks.</p>

<!--more-->


<p>If you&rsquo;re looking for a long post on how
much rails API sucks, you&rsquo;re going to be sorely disappointed. Remember,
I do like rails. It&rsquo;s an easy framework for anyone to get into. If
you&rsquo;re looking to build simple
<a href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a>
applications, rails is hugely productive. Just a simple set of terminal
commands and you have a full working application. Hell, no code
required. The problem is that all the work is hidden by code generation.
Once you have to do anything out of the ordinary, your stuck looking up
the documentation.</p>

<p>Why is this so difficult? Because the API isn&rsquo;t all
that great. There are multiple ways to do everything. Without
consistency, it&rsquo;s a matter of memorization, and who has time to memorize
when work needs to be done. The problem is compounded when you add in
the multitude of <a href="http://en.wikipedia.org/wiki/RubyGems">gems</a> into your
project. All of these work, as <a href="http://en.wikipedia.org/wiki/Black_box">black
boxes</a>. You just run random
commands and something happens. These commands are all different and you
hope you don&rsquo;t get them confused.</p>

<p>Just for a test, I looked up the new
&ldquo;respond_with&rdquo; command on Google. The first link to actual
documentation is the seventh one, and that is with me looking up the
exact command. The documentation is just bad. I still have to look up
things every time I have my editor open. There are ways to avoid this,
though. We could use an editor with code completion, but doesn&rsquo;t that
just hide the underlying problem? What we really need is a better API.</p>

<p>Now, I&rsquo;m picking on Rails a little bit, and that framework doesn&rsquo;t
deserve all the negativity alone. .NET has the same problems, but it&rsquo;s
hidden behind the &ldquo;Visual Studio&rdquo; facade. With
<a href="http://en.wikipedia.org/wiki/Intellisense">intellisense</a> (code
completion), I can see the list of methods on a class and descriptions
of them at a simple control and space. I admit that I do this quite a
bit with new libraries.</p>

<p>If you designed your APIs with consistency in
mind, your users wouldn&rsquo;t need to constantly reference the
documentation. Focus on the language (as in spoken) of your API. Speak
it out loud and just listen for the sentences that come out. Are you
hearing coherent thoughts? Do each of the sentences from your classes
and methods sound like they come from the same paper? Your methods
define your sentences, your classes define your paragraphs, and your
namespaces define your pages.</p>

<p>You&rsquo;ll find out that when your API makes
sense to you, it will start to make sense to your users. Too many APIs
try to focus too much on functionality and ignore verbal cohesion.
Others go the opposite route and become overly verbose. (I&rsquo;m looking at
you testing frameworks). There is a happy medium to be found.</p>

<p>Just remember, when your users are complaining about your documentation, they
are really complaining about your API.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Cloud, Meet Enterprise Software]]></title>
    <link href="http://www.codefixes.com/2010/11/cloud-meet-enterprise-software/"/>
    <updated>2010-11-16T00:00:00-06:00</updated>
    <id>http://www.codefixes.com/2010/11/cloud-meet-enterprise-software</id>
    <content type="html"><![CDATA[<p>What defines enterprise level software? It&rsquo;s usually defined by software
written for groups or organizations rather than for a single person.
Enterprise software has historically been large, expensive systems
backed by huge companies such as Oracle and Microsoft. Has this changed?
&ldquo;Cloud&rdquo; computing has been promoted for a while as <strong>the</strong> solution for
downsizing the costs of running enterprise level systems. Wouldn&rsquo;t it be
great to outsource the entire server room and not worry about hardware
failures ever again? It sounds like a fantastic idea, but it hasn&rsquo;t
caught on in large organizations.</p>

<!--more-->


<p>There are various reasons why, and I
won&rsquo;t go into detail on all of them. One of the reasons is that
corporations are slow to move to new technology. They want it to be
bullet proof; they want it backed by a company so they can get support
now. Enterprise software has to meet these criteria. Of course the cloud
has large backers also, like Amazon and Microsoft, but they don&rsquo;t work
well with each other.</p>

<p>Let&rsquo;s not forget social media. You have your
facebook account, twitter account, and google account. You update people
about where you are on foursquare. You post videos of yourself on
youtube, you checkout your friends on flickr, and most of all, you have
to know what your friends are doing right now. Communication used to be
simple when there was email and telephones, but now there are dozens of
ways to communicate.</p>

<p>Now if you&rsquo;re a corporate man like myself, you
understand a different version of &ldquo;social media.&rdquo; You know it as
voicemail and email. You search the web on your BlackBerry more than you
do on your computer. You&rsquo;re a proud corporate man. You segregate
yourself from the rest of the social world. You know enterprise as the
Microsoft Office suite.</p>

<p>So what&rsquo;s different between corporate enterprise
software and cloud services? One word, integration. You know if you buy
Exchange Server, it will run perfectly with your Windows XP clients, and
run beautifully on Windows Server 2008. Your email syncs to your phone
and people can schedule meetings while knowing if you are available.
Cloud services are run by multiple companies with little to no
integration. It&rsquo;s in their best interest to not cooperate with their
competitors. You can see this just by the fight between Google and
FaceBook. We have been using Microsoft for so long that it&rsquo;s in our
blood. It will be hard to dilute it.</p>

<p>Along comes <a href="http://twitter.com/#!/colinmyoung">this college student</a>
pitching his simple idea to
a large crowd last Friday night at Startup Weekend. Why not take one
step forward? Why not create a simple interface to all of the services
you use? In comes <a href="http://ubercmd.com/">ubercmd</a>. Finally you wouldn&rsquo;t
have to worry about syncing all your contacts to five different
locations. The interface is a simple, intuitive, fast command line type
page. For a terminal junkie like myself, this is great. Just type email
<a href="&#109;&#x61;&#105;&#108;&#x74;&#111;&#58;&#x6d;&#x61;&#x72;&#107;&#x40;&#99;&#x6f;&#x64;&#101;&#102;&#46;&#46;&#x2e;">&#109;&#x61;&#114;&#x6b;&#64;&#99;&#111;&#100;&#101;&#x66;&#x2e;&#46;&#46;</a> oh wait, it&rsquo;s already there. And it&rsquo;s showing my twitter
and facebook accounts. Now three ways of contacting me instead of just
the one you were about to do. It&rsquo;s so simple, yet so brilliant.</p>

<p>So how
does this tie into enterprise software? It is one step forward to
interoperability between all the software you use in the cloud. That
means we can stop paying the Microsoft tax and move towards simpler
SaaS. Small companies can finally compete without having to pay
outrageous pricing. It would be great if their 37 signals accounts would
connect with their Google apps accounts. Finally the level of
connectivity that Microsoft and IBM junkies have had forever.</p>

<p>Of course,
this is a pipe dream, for now. All they have is a demo. This is where
you can help. This group is in the running to win a trip to meet VCs in
California. You can vote for them to win so this dream can finally come
true. There are just so many possibilities on how this idea can grow and
I&rsquo;ll be the first to sign up when a public API goes live. Go check out
<a href="http://globalstartupbattle.com/vote/">startup weekend&rsquo;s winning ideas</a>
and vote for the one you want to see win.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[UI Programming: You're Doing It Wrong]]></title>
    <link href="http://www.codefixes.com/2010/11/ui-programming-youre-doing-it-wrong/"/>
    <updated>2010-11-11T00:00:00-06:00</updated>
    <id>http://www.codefixes.com/2010/11/ui-programming-youre-doing-it-wrong</id>
    <content type="html"><![CDATA[<p><img class="right" src="http://www.codefixes.com/images/blog/hourglass.jpg" title="&#34;hourglass&#34;" alt="&#34;hourglass&#34;">
Let me ask you a question; a serious question. How are you handling events
in your GUI applications? Are you just running code whenever an event
comes? Is your application trying to work well with others?</p>

<p>Now tell me, does it match the following?</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="k">public</span> <span class="k">void</span> <span class="nf">OnClick</span><span class="p">(</span> <span class="n">EventHandlerArgs</span> <span class="n">args</span> <span class="p">)</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>    <span class="n">ThreadPool</span><span class="p">.</span><span class="n">QueueUserWorkItem</span><span class="p">(</span> <span class="n">_</span> <span class="p">=&gt;</span> <span class="n">DoTheWork</span><span class="p">(</span> <span class="p">)</span> <span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>If it doesn&rsquo;t, you may be irritating your users.</p>

<!--more-->


<p>So what can we do? Well your processing power is a limited resource, especially when we talk
about the user interface. You need to treat it like the rare commodity
that it is. If the cost of processing power on the user interface thread
actually did cost you money, you would do anything you could to avoid
using it. Well that&rsquo;s how your user feels. Every millisecond on the the
UI thread is another millisecond your user has to wait. It might not
seem like much, but an unresponsive UI is a problem. It&rsquo;s hard to see
and even harder to test. You just know if something is unresponsive.</p>

<p>To fix this we need to move everything off the UI thread&hellip; I mean
everything. Well, as you know, not everything can be on the background
threads. You need still need to handle events and physically update the
screen. These things are inherent to operating systems and GUI
frameworks. Even <em>if</em> you could, the display updates all at once. So we
work around these things by doing the bare minimum. The instant we are
on the UI thread, we queue up work on the thread pool.</p>

<p>I told you before that multi-threading is difficult. Well, that is true, but it&rsquo;s an issue
you will have to deal with eventually. I will go into more detail in the
future, but for now, just lock everything that you need. Don&rsquo;t worry
about efficiency on the background threads. It&rsquo;s already in the
background, so it shouldn&rsquo;t bother the user to wait an extra hundred
milliseconds. If you find that something is taking too long because it&rsquo;s
waiting on a lock, then you can go and optimize it using functional
style programming or non blocking operations.</p>

<p>Now the GUI is responsive.  Button presses are handled instantaneously and switching tabs happen
right when the user clicks. Everything is great, except for the fact
that there is no response to a user clicking the button. All it does is
press in and out. No user feedback besides that. What happens if the
background process requires multiple seconds to run? Well, you need to
notify the UI thread.</p>

<p>This is where the BackgroundWorker comes into play. The ThreadPool.QueueUserWorkItem is fine for those quick processes
you need to fire off, but we need something for the long running tasks.
BackgroundWorker can access the UI thread whenever it&rsquo;s needed. That
means you can update the status of the process and notify of completion
whenever you need and not worry about whether or not you&rsquo;re on the
correct thread.</p>

<p>Let&rsquo;s look at how we use it.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="c1">// Create the worker </span>
</span><span class='line'><span class="kt">var</span> <span class="n">worker</span> <span class="p">=</span> <span class="k">new</span> <span class="n">BackgroundWorker</span> <span class="p">{</span>
</span><span class='line'>    <span class="n">WorkerReportsProgress</span> <span class="p">=</span> <span class="k">true</span><span class="p">,</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>We&rsquo;re reporting progress in our example, so we need to tell .NET about that.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="c1">// Does the actual work </span>
</span><span class='line'><span class="n">worker</span><span class="p">.</span><span class="n">DoWork</span> <span class="p">+=</span> <span class="p">(</span> <span class="n">s</span><span class="p">,</span> <span class="n">a</span> <span class="p">)</span> <span class="p">=&gt;</span> <span class="p">{</span>
</span><span class='line'>    <span class="kt">var</span> <span class="n">w</span> <span class="p">=</span> <span class="p">(</span> <span class="n">BackgroundWorker</span> <span class="p">)</span><span class="n">s</span><span class="p">;</span>
</span><span class='line'>    <span class="k">for</span> <span class="p">(</span> <span class="kt">int</span> <span class="n">i</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="p">&lt;</span> <span class="m">10</span><span class="p">;</span> <span class="p">++</span><span class="n">i</span> <span class="p">)</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="c1">// Slow process... zzzz</span>
</span><span class='line'>        <span class="n">Thread</span><span class="p">.</span><span class="n">Sleep</span><span class="p">(</span> <span class="m">1000</span> <span class="p">);</span>
</span><span class='line'>
</span><span class='line'>        <span class="c1">// Report the progress</span>
</span><span class='line'>        <span class="n">w</span><span class="p">.</span><span class="n">ReportProgress</span><span class="p">(</span> <span class="n">i</span> <span class="p">*</span> <span class="m">10</span> <span class="p">);</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1">// We&#39;re done </span>
</span><span class='line'>    <span class="n">a</span><span class="p">.</span><span class="n">Result</span> <span class="p">=</span> <span class="s">&quot;Success&quot;</span><span class="p">;</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>Here we&rsquo;re running a slow process to show that the user interface is still usable.
If you did this on the UI thread, the application would lock up for a
full ten seconds and would never update the display. In this example,
it&rsquo;s harmlessly locking up a background thread.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="c1">// Will run on the UI thread</span>
</span><span class='line'><span class="n">worker</span><span class="p">.</span><span class="n">ProgressChanged</span> <span class="p">+=</span> <span class="p">(</span> <span class="n">s</span><span class="p">,</span> <span class="n">a</span> <span class="p">)</span> <span class="p">=&gt;</span> <span class="p">{</span>
</span><span class='line'>    <span class="c1">// Progress has changed</span>
</span><span class='line'>    <span class="n">progressBar</span><span class="p">.</span><span class="n">Value</span> <span class="p">=</span> <span class="n">a</span><span class="p">.</span><span class="n">ProgressPercentage</span><span class="p">;</span>
</span><span class='line'><span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// Also run on the UI thread </span>
</span><span class='line'><span class="n">worker</span><span class="p">.</span><span class="n">RunWorkerCompleted</span> <span class="p">+=</span>
</span><span class='line'>    <span class="p">(</span> <span class="n">s</span><span class="p">,</span> <span class="n">a</span> <span class="p">)</span> <span class="p">=&gt;</span> <span class="n">MessageBox</span><span class="p">.</span><span class="n">Show</span><span class="p">(</span> <span class="p">(</span> <span class="kt">string</span> <span class="p">)</span><span class="n">a</span><span class="p">.</span><span class="n">Result</span> <span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now we can update the user interface. The progress bar will update every second, and we didn&rsquo;t
have to check which thread we&rsquo;re on.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="c1">// Run the worker on the threadpool </span>
</span><span class='line'><span class="n">worker</span><span class="p">.</span><span class="n">RunWorkerAsync</span><span class="p">(</span> <span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>That&rsquo;s all that&rsquo;s required to run something in the background. Why would you even
think of trying to do it in the foreground?</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Think Functional: Lambdas and LINQ]]></title>
    <link href="http://www.codefixes.com/2010/11/think-functional-lambdas-and-linq/"/>
    <updated>2010-11-09T00:00:00-06:00</updated>
    <id>http://www.codefixes.com/2010/11/think-functional-lambdas-and-linq</id>
    <content type="html"><![CDATA[<p>If you haven&rsquo;t read the previous post,
<a href="http://www.codefixes.com/2010/11/think-functional-immutable-types-and-idempotence/">Immutable Types and Idempotence</a>,
I recommend doing so now. It will help you get a better understanding of
what I&rsquo;ll be talking about here. Now that we have basic knowledge of
<em>what</em> a pure method really is, we need to figure out how to use it.
It&rsquo;s not that difficult, but the syntax may require some getting used
to. We&rsquo;ll be using .NET&rsquo;s LINQ component to describe how to use lambdas
to increase your code efficiencies, but these ideas travel well into the
C++ world using either
<a href="http://www.boost.org/doc/libs/1_44_0/doc/html/lambda.html">Boost.Lambda</a>
or
<a href="http://en.wikipedia.org/wiki/C++0x#Lambda_functions_and_expressions">C++0x</a>,
if your compiler supports it.</p>

<!--more-->


<p>As we recall, we were creating idempotent
(pure) methods and forcing the rules by using immutable objects. We can
easily use these ideas to create queries and projections directly in
code, where the original data is not modified. The benefit here, again,
is that this will scale. Also, as will see soon, the application will
run faster by the magic of
<a href="http://en.wikipedia.org/wiki/Lazy_evaluation">lazy evaluation</a>.</p>

<p>For example, let us say we have a list of ten thousand orders.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="c1">// Load all the orders IEnumerable&lt;Order&gt; orders = OrderRepository.GetAllOrders( );</span>
</span></code></pre></td></tr></table></div></figure>


<p>Notice that the result returned
is a generic IEnumerable. What happens here is that GetAllOrders doesn&rsquo;t
necessarily need to return the full list of orders, it can skip this
step and return the <em>intent</em> of getting the full list of orders. The
IEnumerable is actually hiding what the GetAllOrders method is really
returning, an
<a href="http://msdn.microsoft.com/en-us/library/system.linq.iqueryable.aspx">IQueryable</a>.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="k">public</span> <span class="k">static</span> <span class="k">class</span> <span class="nc">OrderRepository</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>    <span class="k">public</span> <span class="k">static</span> <span class="n">IQueryable</span><span class="p">&lt;</span><span class="n">Order</span><span class="p">&gt;</span> <span class="n">GetAllOrders</span><span class="p">(</span> <span class="p">)</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>        <span class="k">return</span> <span class="n">orders</span><span class="p">.</span><span class="n">AsQueryable</span><span class="p">(</span> <span class="p">);</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>The IQueryable interface provides a decoupling of the query
source from the logic to be run upon it. In other words, the IQueryable
interface stores the methods (lambdas) to be called upon its source in a
tree structure. Later, when you want to iterate over the list, it will
run the commands live on the data. This can significantly reduce the
amount of data returned and won&rsquo;t force you to create multiple lists of
the same data in the various steps of the query. Haskell takes this one
step further and actually allows infinite lists. This may seem odd to
you, but since everything is lazily loaded, the list doesn&rsquo;t need to
actually exist in memory.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='hs'><span class='line'><span class="nf">take</span> <span class="mi">5</span> <span class="p">[</span><span class="mi">1</span><span class="o">..</span><span class="p">]</span>
</span><span class='line'><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">]</span>
</span></code></pre></td></tr></table></div></figure>


<p>Also, the IQueryable defines an immutable type, so
it may be able to run on multiple cores. This is not always the case,
though. For example, an IQueryable can be attached to a database, and
therefore only run one SQL command. For now, let&rsquo;s assume the list is
stored in a randomly accessible location such as in memory.</p>

<p>What we can
do with these queryable objects is throw expressions or lambdas at them.
The IQueryable interface defines a long list of methods that can be
executed, such as Where, Select, FirstOrDefault, etc. Each of these
methods take in a lambda and will run that anonymous method against the
function. For example, if we wanted to reduce our list of orders down to
only the ones that were over $1000, we could do the following.</p>

<p>Lambdas in C# use a new operator that looks like an arrow (=>). This may be
confusing at first, but generally becomes easier to comprehend as time
goes on. I find it easier to talk the expression out loud and replace
&ldquo;=>&rdquo; with &ldquo;such that.&rdquo; In the following example, I would say &ldquo;Expensive
orders = orders where &lsquo;o&rsquo; such that &lsquo;o&rsquo; dot total price is greater than
one thousand.&rdquo; If you can speak it out loud, it will be easier to
understand. Of course, lambdas go deeper than this example, but you can
find many <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx">other examples of the syntax</a> by
searching the web.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="kt">var</span> <span class="n">orders</span> <span class="p">=</span> <span class="n">OrderRepository</span><span class="p">.</span><span class="n">GetAllOrders</span><span class="p">(</span> <span class="p">);</span>
</span><span class='line'><span class="kt">var</span> <span class="n">expensiveOrders</span> <span class="p">=</span> <span class="n">orders</span><span class="p">.</span><span class="n">Where</span><span class="p">(</span> <span class="n">o</span> <span class="p">=</span><span class="err">\</span><span class="p">&gt;</span> <span class="n">o</span><span class="p">.</span><span class="n">TotalPrice</span> <span class="err">\</span><span class="p">&gt;</span> <span class="m">1000.0</span><span class="n">M</span> <span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>As I said before, the IQueryable
is considered an immutable type. It will return a new query object every
time you add more expressions to it. In this case, we now have a new
query stored in expensiveOrders. The query stores a series of
expressions for later use, allowing it to be lazily invoked. This can
save us a tremendous amount of CPU work. If we did the above using a
simple foreach loop, it may take a long time to run through all of them.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="kt">var</span> <span class="n">expensiveOrders</span> <span class="p">=</span> <span class="k">new</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">Order</span><span class="p">&gt;(</span> <span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="k">foreach</span><span class="p">(</span> <span class="kt">var</span> <span class="n">order</span> <span class="k">in</span> <span class="n">orders</span><span class="p">)</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>    <span class="k">if</span><span class="p">(</span> <span class="n">order</span><span class="p">.</span><span class="n">TotalPrice</span> <span class="p">&gt;</span> <span class="m">1000.0</span><span class="n">M</span> <span class="p">)</span>
</span><span class='line'>        <span class="n">expensiveOrders</span><span class="p">.</span><span class="n">Add</span><span class="p">(</span> <span class="n">order</span> <span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>In this case, the program would
be forced to loop through every order, even though they may not be all
used. In a user interface, you can&rsquo;t possibly show all the results of
this query on the screen simultaneously. It could require many greater
magnitudes of view space than the screen offers. We would need to
display the list in pages. Of course, in the previous example, even
though we may only show ten results, all ten thousand original orders
would need to be checked.</p>

<p>However, if we stuck with LINQ, the query
won&rsquo;t be run until it is finally forced.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="kt">int</span> <span class="n">pageSize</span> <span class="p">=</span> <span class="m">10</span><span class="p">;</span>
</span><span class='line'><span class="kt">int</span> <span class="n">page</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// Query first created</span>
</span><span class='line'><span class="kt">var</span> <span class="n">orders</span> <span class="p">=</span> <span class="n">OrderRepository</span><span class="p">.</span><span class="n">GetAllOrders</span><span class="p">(</span> <span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// Not run yet</span>
</span><span class='line'><span class="kt">var</span> <span class="n">expensiveOrders</span> <span class="p">=</span> <span class="n">orders</span><span class="p">.</span><span class="n">Where</span><span class="p">(</span> <span class="n">o</span> <span class="p">=&gt;</span> <span class="n">o</span><span class="p">.</span><span class="n">TotalPrice</span> <span class="p">&gt;</span> <span class="m">1000.0</span><span class="n">M</span> <span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// Still not run</span>
</span><span class='line'><span class="kt">var</span> <span class="n">displayedOrders</span> <span class="p">=</span> <span class="n">expensiveOrders</span>
</span><span class='line'>    <span class="p">.</span><span class="n">Skip</span><span class="p">(</span> <span class="n">page</span> <span class="p">*</span> <span class="n">pageSize</span> <span class="p">)</span>
</span><span class='line'>    <span class="p">.</span><span class="n">Take</span><span class="p">(</span> <span class="n">pageSize</span> <span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// Now the query is finally run</span>
</span><span class='line'><span class="k">foreach</span><span class="p">(</span> <span class="kt">var</span> <span class="n">order</span> <span class="k">in</span> <span class="n">displayedOrders</span> <span class="p">)</span>
</span><span class='line'>    <span class="n">DisplayOrder</span><span class="p">(</span> <span class="n">order</span> <span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Although it&rsquo;s not quickly apparent, the query is finally run before being passed to
DisplayOrders. In this case, only ten results are needed. Because of the
use of LINQ, the query will be stopped short once ten items are taken
from the results.</p>

<p>Now that we know about pure methods and lazy
invocation, let&rsquo;s use that knowledge to actually build faster code. Next
time, we&rsquo;ll take a look at
<a href="http://en.wikipedia.org/wiki/Parallel_Extensions#Parallel_LINQ">PLINQ</a>
and the <a href="http://en.wikipedia.org/wiki/Parallel_Extensions">Parallel Extensions</a> library.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Think Functional: Immutable Types and Idempotence]]></title>
    <link href="http://www.codefixes.com/2010/11/think-functional-immutable-types-and-idempotence/"/>
    <updated>2010-11-07T00:00:00-05:00</updated>
    <id>http://www.codefixes.com/2010/11/think-functional-immutable-types-and-idempotence</id>
    <content type="html"><![CDATA[<p>I already talked about functional programming recently in a
<a href="http://www.codefixes.com/2010/11/cpu-speeds-have-maxed-out-now-what/">prior article</a>,
however I state that functional programming is difficult (but in a
different way). The problem is it looks like you have to forget
everything you learned about object oriented and procedural programming.
Seems like a waste to throw away all that good knowledge to blindly go
down a path that hasn&rsquo;t even hit mainstream yet. You don&rsquo;t have to. You
can start programming &ldquo;functionally&rdquo; right now no matter what language
you use.</p>

<!--more-->


<p>Functional programming doesn&rsquo;t require esoteric languages. It&rsquo;s
more of a mind set than anything. Sure you could go right now and
download <a href="http://www.erlang.org/">Erlang</a> or
<a href="http://www.haskell.org/">Haskell</a>, but I can tell you that you&rsquo;re about
to go down a long, difficult road. The problem is you not only have to
learn a new language, but you still need to learn functional
programming. Instead, I&rsquo;ll be writing a series of articles on how to
implement functional ideas in your current language.</p>

<p>So, where do we begin? Probably the first idea to learn is about
<a href="http://en.wikipedia.org/wiki/Immutable_object">immutable objects</a>. The general
idea is that once an object is created, it can never be changed. Let
that sink in for a second. If you have never created immutable types
before, this may seem strange. In C#, for example, you can see a few
areas where immutable types are present. Take the C# string type. Once
you create a string, it can never be changed. All the methods return a
new string with whatever changes you made.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="kt">string</span> <span class="n">hello</span> <span class="p">=</span> <span class="s">&quot;hello&quot;</span><span class="p">;</span>
</span><span class='line'><span class="kt">string</span> <span class="n">world</span> <span class="p">=</span> <span class="s">&quot;world&quot;</span><span class="p">;</span>
</span><span class='line'><span class="kt">string</span> <span class="n">helloWorld</span> <span class="p">=</span> <span class="kt">string</span><span class="p">.</span><span class="n">Join</span><span class="p">(</span> <span class="s">&quot; &quot;</span><span class="p">,</span> <span class="k">new</span><span class="p">[</span> <span class="p">]</span> <span class="p">{</span> <span class="n">hello</span><span class="p">,</span> <span class="n">world</span> <span class="p">}</span> <span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>In the prior
example, both strings &ldquo;hello&rdquo; and &ldquo;world&rdquo; are unchanged by any methods.
You <em>can</em> set a reference to a new reference with different data, but
the original data will remain unchanged until its garbage collected. The
benefit here is that we now have a strict rule we can leverage when it
comes to threading. Because the object can never change, there won&rsquo;t be
any issues with thread safety. If two threads try to access that same
reference, no big deal. There will be no concern of one thread changing
the data from under the nose of the other.</p>

<p>So, how do we define an
immutable type? This is where things get a little hazy. There are no
strict rules that governs immutability in many object oriented
languages. In C#, we can create class members that are
<a href="http://msdn.microsoft.com/en-us/library/acdd6hb7(v=VS.100).aspx">readonly</a>.
This allows the data to be set within the constructors only, and then be
set in stone.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="k">public</span> <span class="k">class</span> <span class="nc">ImmutableClass</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>  <span class="k">private</span> <span class="k">readonly</span> <span class="kt">int</span> <span class="n">val</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">public</span> <span class="kt">int</span> <span class="n">Val</span>
</span><span class='line'>  <span class="p">{</span>
</span><span class='line'>      <span class="k">get</span> <span class="p">{</span> <span class="k">return</span> <span class="n">val</span><span class="p">;</span> <span class="p">}</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>  
</span><span class='line'>  <span class="k">public</span> <span class="nf">ImmutableClass</span><span class="p">(</span> <span class="kt">int</span> <span class="k">value</span> <span class="p">)</span>
</span><span class='line'>  <span class="p">{</span>
</span><span class='line'>      <span class="k">this</span><span class="p">.</span><span class="n">val</span> <span class="p">=</span> <span class="k">value</span><span class="p">;</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>In C++, we don&rsquo;t have that option because there&rsquo;s no such thing as the readonly
type. In that case, we need to create class methods that are
<a href="http://en.wikipedia.org/wiki/Idempotence">idempotent</a>. Idempotent means
that the method has no side effects, however, what does that really
mean? My understanding of this is that the code will not make any
changes to any existing data or interface. It won&rsquo;t change any
pre-existing data. It also won&rsquo;t make any calls outside that may make a
change, such as doing any input or output. Basically, if you call a
method, the output will be exactly the same if you call it again with
the same parameters. In other words, the code has &ldquo;no side effects.&rdquo; If
all your methods are like this, you all of a sudden have an immutable
type.</p>

<p>In C++, this is done by adding the <strong>const</strong> keyword to the end of methods.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='cpp'><span class='line'><span class="kt">int</span> <span class="n">ExampleClass</span><span class="o">::</span><span class="n">Multiply</span><span class="p">()</span> <span class="k">const</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>  <span class="k">return</span> <span class="k">this</span><span class="o">-&gt;</span><span class="n">value1</span> <span class="o">*</span> <span class="k">this</span><span class="o">-&gt;</span><span class="n">value2</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>This isn&rsquo;t a C++ only idea,
however, other languages may not have the same keyword. The idea to take
from this is to create classes that follow these rules. You don&rsquo;t
specifically need the compiler to force these rules for you, although it
does help. That&rsquo;s where functional languages come into play. They will
force these rules on your code for you.</p>

<p>Now you have an understanding of
the basic rules behind functional programming. Next time we&rsquo;ll go into
more of the ideas on using idempotent methods in real world ways. We&rsquo;ll
also discuss how you can actually connect these &ldquo;functional&rdquo; methods to
standard methods.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Some of my past projects]]></title>
    <link href="http://www.codefixes.com/2010/11/some-of-my-past-projects/"/>
    <updated>2010-11-04T00:00:00-05:00</updated>
    <id>http://www.codefixes.com/2010/11/some-of-my-past-projects</id>
    <content type="html"><![CDATA[<p>Over the years, I&rsquo;ve of course worked on a ton of projects, and some of them I
open source. Usually I do this if the project was school related, back when I
was in college, or I want to hand over the project to the community. Of course,
neither go very far after that since it seems like you need to be known and you
actually have to build something useful.  Anyway, here I&rsquo;m going to list some
of those projects and where you can find them.</p>

<!--more-->


<p>Back when I was young, I made a program that converted a text file into an exe.
This allowed shareware vendors to create self running catalogs. It was a pretty
neat program, and had search, colors, mouse support, etc. I called it CatGen,
and I even sold a copy or two.  Not technically open source, but it built you a
.BAS file (QBasic/QuickBasic) that included the text file. You can find it here
(warning, not coming from a controlled source):
<a href="http://piotrkosoft.net/pub/mirrors/simtelnet/msdos/basic/catgen30.zip">CatGen 3.0</a>.</p>

<p>I went on and started looking into 3D graphics, and at one point I wanted to
become a game programmer. I studied all the latest books on OpenGL, DirectX,
SDL, etc. It was fun, and I created my own game engine from it. I submitted it
as my senior design project in undergrad. It was a full blown Quake 2 engine
including rendering, physics, animations, sound, and music. I have to go find
that code.</p>

<p><img src="http://www.codefixes.com/images/blog/screenshot1.jpg" title="&#34;Quake 2 style engine&#34;" alt="&#34;Quake 2 style engine&#34;"></p>

<p>I went on to work for Motorola after college. I was working in a research and
design group in the cell phone division. I was actually working with the people
who designed the original RAZR, and my pride and joy was the &ldquo;morphing&rdquo; phone
called the MOTOROKR E8.</p>

<p><img src="http://www.codefixes.com/images/blog/motorola-rokr-e8-combo.jpg" title="&#34;Motorola ROKR E8&#34;" alt="&#34;Motorola ROKR E8&#34;"></p>

<p>I wrote all the software for the original prototype, and helped in analyzing
and fine tuning the morphing, capacitive sensor, and the
<a href="http://en.wikipedia.org/wiki/Haptic_technology">haptics</a>. By the way, the
haptics on this phone were amazing. Pushing down on the buttons felt exactly
like a button, even though the keyboard didn&rsquo;t move.</p>

<p>I decided to move on from there when the company was doing poorly, but I did
take something with me. I took the idea I was using for the user interface and
made it my own open source project (with the okay from my boss at the time). I
called it <a href="https://sourceforge.net/projects/miniui/">MiniUI</a>. This was a
hardware accelerated, <a href="http://www.lua.org/">scriptable</a> user interface. It
allowed all the effects we take for granted on our smartphones now to be
created simply and easily through XML and simple scripts. I wrote two papers on
the project which can be found through the following:</p>

<ul>
<li><a href="http://sourceforge.net/projects/miniui/files/Documentation/1.0/MiniUI.pdf/download">http://sourceforge.net/projects/miniui/files/Documentation/1.0/MiniUI.pdf/download</a></li>
<li><a href="http://sourceforge.net/projects/miniui/files/Documentation/1.0/ctirs08_submission_4.pdf/download">http://sourceforge.net/projects/miniui/files/Documentation/1.0/ctirs08_submission_4.pdf/download</a></li>
</ul>


<p>I also have a <a href="http://video.google.com/videoplay?docid=-4422339729517928865#">demonstration video</a>, but it
is pretty low quality and the recording was very laggy (hence the tearing on
the screen).</p>

<p>To this day, that project still gets downloads, but I&rsquo;m not sure why. It&rsquo;s now
2-3 years dated. It also started getting more hits since I started this blog,
but that is probably just be coincidence. Otherwise, I&rsquo;d start believing you
guys are stalking me.</p>

<p>Lastly, we come to my latest project. At my company, I created a data access
layer for an application framework we use from
<a href="http://www.aptify.com/Home.aspx">Aptify</a>. It&rsquo;s an adapter of NHibernate and
NHibernate.Linq to their proprietary system. It&rsquo;s actually fairly complex, and
after doing it I wonder why I finished it. Now that it&rsquo;s done, though, we&rsquo;re
loving it. I submitted it to Aptify for their Aptify Innovations Award contest.
I was one of the top finalists and spoke at their user conference in Las Vegas.
After presenting my work to their community, the community voted me as the
winner.</p>

<p>So I guess that makes me an award winning developer, although it&rsquo;s a fairly
niche area. You can find my project up on bitbucket at:
<a href="http://bitbucket.org/markglenn/apics.core/src">http://bitbucket.org/markglenn/apics.core/src</a>.</p>

<p>So what now? Well I&rsquo;m currently working on a commercial client product in the
message queuing market. Hopefully I can get that to the market in the next
couple of months. In the future I&rsquo;ll discuss more about the product as I build
it. For one, I have a lot of interesting things to talk about in regards to
some of the tools and middleware I&rsquo;m using to create it.</p>

<p>Also, again, I&rsquo;m going to <a href="http://startupweekend.org/">Startup Weekend</a> next
weekend in <a href="http://chicago.startupweekend.org/">Chicago</a>. Actually if you go to
that link, the <a href="http://chicago.startupweekend.org/coders'-survival-guide-to-startup-weekend/">top story</a>
(as of this writing) may <a href="http://www.codefixes.com/2010/11/coders-survival-guide-to-startup-weekend/">look familiar</a>.
Yes, it&rsquo;s my article!  Chris, one of the people running Chicago Startup
Weekend, asked to republish my article on the site. So I&rsquo;m a proud guest writer. Not bad for a guy who got B&rsquo;s and C&rsquo;s
in english and writing classes. Anyway, I hope to see you there.  Also make
sure you have your <a href="http://www.eventbrite.com/event/936652553">tickets for the event</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[CPU speeds have maxed out... now what?]]></title>
    <link href="http://www.codefixes.com/2010/11/cpu-speeds-have-maxed-out-now-what/"/>
    <updated>2010-11-03T00:00:00-05:00</updated>
    <id>http://www.codefixes.com/2010/11/cpu-speeds-have-maxed-out-now-what</id>
    <content type="html"><![CDATA[<p>So, you now have this 8 core powerhouse. It has more horsepower than your old
Mustang, but your code is only using 1/8th of that power. How come? Because
while the rules of Moore&rsquo;s law changed, your code hasn&rsquo;t.</p>

<!--more-->


<p>The problem isn&rsquo;t that technology is changing, it&rsquo;s that your language isn&rsquo;t
changing quick enough. Threads are the answer, or they were.  Threads were the
answer a few years back when we had two cores, maybe four. Now we have eight
with sixteen just around the corner. And worse yet, cores may become less
powerful to reduce heat and power.
<a href="http://en.wikipedia.org/wiki/Arm_architecture">ARM</a> processors have moved on
to the <a href="http://en.wikipedia.org/wiki/Netbook">personal computer</a> and don&rsquo;t seem
to be <a href="http://simmtester.com/page/news/shownews.asp?num=13364">slowing down</a>.
ARMs are a form of
<a href="http://en.wikipedia.org/wiki/Reduced_instruction_set_computer">RISC</a> processor
or &ldquo;Reduced Instruction Set Computer.&rdquo; This means that it has a smaller
instruction set than the laptop you have now. An instruction that takes one
tick may take two in the future.</p>

<p>Okay, what gives? Why go backwards? Because it&rsquo;s smaller, more efficient, less
power hungry, etc&hellip; Smack a few dozen of those cores together and you have one
fast machine. Now, I can&rsquo;t predict the future obviously, nor am I marking the
future death of the x86 instruction set. I&rsquo;m just pointing out one possibility
to show my point.</p>

<p>Okay, what is my point? You&rsquo;re coding style will have to change if you want to
stay &ldquo;future proof.&rdquo; <a href="http://blogs.msdn.com/b/jmstall/archive/2008/01/30/why-threading-is-hard.aspx">Threading is difficult</a>.
It&rsquo;s error prone, hard to predict, even harder to optimize. And what do you get
out of this headache? Code that still takes only 1/8th of the CPU power
available to it. The problem is, most of the time your code is waiting for
input, an event to fire, or some I/O process to complete.  You have to manage
separate threads just to do the same job that was done on DOS years ago. Users
expect responsive applications. If you want the truth, try using iTunes on a
Windows PC.</p>

<p>So some languages have added features to help with calming your worried mind. For
example, .NET added <a href="http://en.wikipedia.org/wiki/Parallel_Extensions">Parallel Extensions</a>
and the <a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx">Reactive Extensions (Rx)</a>. And
C++ finally added <a href="http://en.wikipedia.org/wiki/C++0x#Lambda_functions_and_expressions">lambda expressions</a>
to the mix (although it was <a href="http://www.boost.org/doc/libs/1_44_0/doc/html/lambda.html">available in boost</a> for a while).
These help reduce the noise of making your code threaded, but still miss out
when it comes to <a href="http://en.wikipedia.org/wiki/Thread_safety">thread safety</a>,
<a href="http://en.wikipedia.org/wiki/Deadlock">deadlocks</a>, or
<a href="http://en.wikipedia.org/wiki/Dining_philosophers_problem">starvation</a>.</p>

<p>You probably know the answer already. People have been blogging about it for a
while now. It&rsquo;s the new kid on the block&hellip; er, well, old kid.  It&rsquo;s
<a href="http://en.wikipedia.org/wiki/Functional_programming">functional programming</a>,
based off of <a href="http://en.wikipedia.org/wiki/Lambda_calculus">lambda calculus</a>
from the 1930s. You may hear it by other names, such as F#, Haskell, Scheme,
Erlang, OCaml, or LINQ.</p>

<p>Wait, LINQ? Yeah, you&rsquo;ve been using functional programming all this time. All
those lambdas you&rsquo;ve been throwing at LINQ are examples of functional
programming. And if you&rsquo;ve done it correctly, they are possibly examples of
<em>purely functional programming</em>. Those lambdas don&rsquo;t have any side effects, so
a search can be run on that list of 10,000 items on all of your cores, and
without any work on your part. Parallel Extensions in .NET 4.0 does all the
heavy lifting for you. This is great news, you say&hellip;</p>

<p>But alas, it&rsquo;s not the final chapter in this story. Parallel Extensions are
great if you constantly have to search for something in a list of 10,000 items,
but your code answers to clicks and I/O events. You have more important things
to do than playing around with something that&rsquo;s of little to no use to the
general coding population, building client applications. What we need is a true
functional language.</p>

<p>And this is where the story ends, for now. Functional programming is the next
logical step. Just imagine a language where you can write all methods, and they
would magically run on other threads when branching, and that they would join
up again when the branches merge. The code could trigger a UI update from one
thread and not care if it&rsquo;s on the UI thread or not. No longer are these your
problems. You now write functions with no side effects; functions that are
<a href="http://en.wikipedia.org/wiki/Idempotence">idempotent</a>. Let the compiler worry
about where the code should run, you have more important things to do.</p>

<p>It has started. Take a look at <a href="http://nodejs.org/">node.js</a>. They use event
driven functions. Most of the time, these functions call out to node.js,
requesting or sending data, and send a callback to be called when it completes.
No waiting.  The server happily handles the I/O in the background and can
process other requests while that Ruby on Rails site just sits there. It&rsquo;s
pretty neat stuff.</p>

<p>You can have this too for your desktop applications.
<a href="http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/default.aspx">F#</a>
brings .NET to the functional world. <a href="http://qt.nokia.com/">Qt</a> has
<a href="http://qthaskell.berlios.de/">qtHaskell</a>.
<a href="http://www.wxwidgets.org/">wxWidgets</a> has
<a href="http://www.erlang.org/doc/apps/wx/chapter.html">wx and Erlang</a>. That means you can
write WPF/Qt/wxWidgets applications that handle everything with event driven
code and purely functional calls. It&rsquo;s available now.</p>

<p>Problem is, functional programming is also hard, but in a different way.  Of
course, that&rsquo;s for another place and time. For now, pick up a copy of
<a href="http://www.amazon.com/gp/product/0596514980?ie=UTF8&amp;tag=codefixes-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0596514980">Real World Haskell</a><img src="http://www.assoc-amazon.com/e/ir?t=codefixes-20&amp;l=as2&amp;o=1&amp;a=0596514980" alt="image" />
or <a href="http://www.amazon.com/gp/product/1933988924?ie=UTF8&amp;tag=codefixes-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=1933988924">Real World Functional Programming: With Examples in F# and C#</a><img src="http://www.assoc-amazon.com/e/ir?t=codefixes-20&amp;l=as2&amp;o=1&amp;a=1933988924" alt="image" />
and start coding.</p>
]]></content>
  </entry>
  
</feed>
