Latest Publications

One Query to Inner Join or Left Join Based on a Flag

I ran into a situation today where the issue at hand was to I had to update a query from a Left Join to an Inner Join. One concern was that some of the consumers of the query needed the Left Join while others now needed an Inner Join of the data.

create table One (
    id int,
    noun vchar(5)
)

insert into One
values
    (1, 'Car'),
    (1, 'Bus'),
    (1, 'Bike'),
    (2, 'Boat'),
    (3, 'Book'),
    (4, 'Sock'),
    (5, 'Rock')

create table Two (
    id int,
    verb vchar(10)
)

insert into Two
values
    (1, 'Rolls'),
    (2, 'Floats'),
    (3, 'Reads...?')

select o.noun, t.verb
from One o
left join Two t
on o.id == t.id
where len(noun) = 4

The Obvious Solutions

There are a couple of solutions that come to mind first off.

  1. Create two procedures, One with an Inner Join and another with an Left Join.
  2. Modify the procedure to take a flag and switch between the two.

The first solution is probably the worst. You not have nearly the exact same code in two places. Where the odds are that in the any future changes to either procedures will not be propagated between them. Likely causing an bug or unintended side effect.

Two Separate Procs

--Proc One
select o.noun, t.verb
from One o
left join Two t
on o.id == t.id
where len(noun) = 4

--Proc Two
select o.noun, t.verb
from One o
join Two t
on o.id == t.id
where len(noun) = 4

The second solution is better because it keeps the code in the same logical place. That way if you update one you will likely think: “Hey, maybe I should update that select too”. Still, it is essentially the same code in two different places, be it in the same proc.

If Not One Then the Other

declare @flag bit
select @flag = 0

if @flag
begin
    --Proc One
    select o.noun, t.verb
    from One o
    left join Two t
    on o.id == t.id
where len(noun) = 4
end
else
begin
    --Proc Two
    select o.noun, t.verb
    from One o
    join Two t
    on o.id == t.id
where len(noun) = 4
end

We Can Do Better

So the next two things that came to mind were

  1. Take the results from the first select, the one with the Left Join, and using an “if” block select the rows in the result with out the nulls produced by the left join.
  2. Use some sort of logical selection in the query clause or a case statement to auto-magically switch between the two behaivors

Now the first option is not a bad solution. Given you know that the data set will always be small and that the cost of the second query is negligible in CPU and the memory.

Select “if / then” select again

declare @flag bit
select @flag = 0

select o.noun, t.verb
into #tempJoin
from One o
left join Two t
on o.id == t.id
where len(noun) = 4

if @flag
begin
    select *
    from #tempJoin
    where verb is not null
end
else
begin
    select *
    from #tempJoin
end

But…

But…

We Should Do Better

Usually any solution that involves “auto-magically” can be flagged right off as impossible, impractical, or a “bad idea” but something about the solution… if possible… seemed like it could be elegant, concise, and practical.

The answer lies in the select “if / then” select again solution. We have a query that returns the results we need in both cases. In one of those cases we just don’t need all of it and we have a if statement select out the nulls returned by the left join.

That logic of if “flag” then “remove the nulls” just has to be moved into the query. Typically there are three ways to do that.

One is to move the logic into a case statement. We could use the case to omit rows when they don’t match what we want but that would produce nulls. Again, what we don’t want.

The second and third are to embed the logic into the Join or the Where clauses of the statement. For the final solution both work but I chose to use the where clause because I believe it was more readable and simpler for other maintainers to understand.

So when you think about it you want to remove the row or keep the row based on the flag. The first thing you should think is AND. You want to mask the data or keep it so an AND will do the job. The next part of your logic will be to match what you want to filter out. That filter with the AND will turn your Left Join into an Inner Join. With that solved you have to find a way to switch that behavior on and off. The way to do that is to use an OR, not at the same level as your AND but inside with the filter. To ignore it, filter or true, or use it, filter or false. If your having trouble following that read though the code and look though the comments.

Both Left and Inner Join in One Select

select o.noun, t.verb
into #tempJoin
from One o
left join Two t
on o.id == t.id
--Our original where clause
where len(noun) = 4
--AND to filter
and (
    --This is our filter; remove nulls
    t.verb is not null
    or
    --When this is true the filter is ignored
    --When this is false the filter works
    @flag = 1
)

So that, in a nut shell is it. You can switch between a Left Join and an Inner Join using a flag using only one select statement and no if blocks or case statements. The real advantage is that there is no code duplication across procedures or inside the proc it’s self.

Literal Strings C#

Something that frequently gets overlooked in C# are Literal Strings or Verbatim Strings. These are strings like any other except that none of the usual escape characters work. You may think, “Well that just sounds like a broke string”, but that’s the point.

Some times you don’t want a backslash to escape the characters in your string. For example when writing paths in Windows to a file or folder.

//This causes issues because \S is not a valid escape
//and \t is valid but you don't want to insert a tab in your string.
s = "C:\SomePath\That you want\to use";
//Escaping the slashes hurts readability and is aggravating to update
s = "C:\\Imagine\\lots\\of\\sub\\directories";

The same is true when trying to write regualar expressions. The symbols to represent digits (\d) and and word characters (\w) are not normally valid escape characters.

//Using \d and \w in a regular string will stop your code from building.
r = new RegEx("Jonny (\d) is \"(\w+)\"");
//Further more escaping the slashes in a RegEx can make the sting hard
//to read or even more confusing to people who don't use RegEx-es.

The solution is to decorate the string with an ‘at’ symbol and turn it into a string literal or verbatim string. What that dose is ignore the slashes in your string so that they can be used literally. Ironic, i know…

//All of these strings hurt the eyes less, build and, in all
//cases except the regular expression, no longer intimidate
s1 = @"C:\SomePath\That you want\to use";
s2 = @"C:\Imagine\lots\of\sub\directories";
//Notice since '\' no longer escapes we prefix the " with a "
//That's the only quark, i swear.
r = new RegEx(@"Jonny (\d) is ""(\w+)""");

Yeah, it’s a simple thing, but lots of people don’t seem to know it. So learn it, use it and make suggest others use it.

The Response to the Changing Requirements of Operations

My friend Eric sent me this link about Careers and Jobs in technology and how the change in expectations from users has shaped how the job is done. I think its a good talk and the speaker covers a lot of his ideas.

4 Steps to Getting Started with Git

Git is a Distributed version control system. If you are programming you should know about and be using version control. Here are 4 easy steps to getting started with Git as your version control.

Now there are two assumptions going into this. The first that you have downloaded and installed Git. The second is that you can navigate to your source from a command line.

Step 1 – Create the Repository

So this is where the prerequisites come in. Using Git Bash, that you have already installed, go to the directory that you have your code in. Tell Git to create a new repository, right where your code is.

user@computer /c/path/to/your/code/
$ git init

You should now see a message telling you that it has created an empty repository in a folder called “.git” in your directory.

Step 2 – Add Your Files

You need to add files that you want into the repository. You do this with the add command. When using add you can supply a filter like “*.cs” or “*.css”. In this example we want to add everything.

user@computer /c/path/to/your/code/ (master)
$ git add *

Step 3 – Verify Your Staged Files (Optional)

With most things in software development it’s not a bad thing to be a little paranoid. However for the reckless, this step is optional. Verify that the files you want are set to be added to the repository.

user@computer /c/path/to/your/code/ (master)
$ git status

Step 4 – Check in Your Files

Now that you have all your files staged and ready, check them in to the repository.

user@computer /c/path/to/your/code/ (master)
$ git commit -m "Your comment goes here"

That’s it. Your done! In the future when you want to add the changes you have made or new files use the add command again. That’s something different about git. You use the add command for changes and new files. Then when you are satisfied with the staged changes call commit again.

That’s the pattern when developing with Git:

  1. Make updates.
  2. Stage the changes.
  3. Commit the changes.

You can even combine step two and three with the -a flag. However, then you couldn’t verify your staged files before the commit…

user@computer /c/path/to/your/code/ (master)
$ git commit -a -m "Your comment goes here"

Using jQuery to Select the Last Node in a Tree

I worked on some code to show the classes that were being used on some div’s for a presentation. I wanted to be able to have the text of the class attribute show in the final container to give an idea of how the layout ended up looking and why it looked that way.

This is basically a problem of finding all the last nodes in every branch of a tree. The div’s in my case were not all the same depth from the top container

<div id="top">
    <div>
        <div></div>
        <div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>
    <div>
        <div>
            <div></div>
            <div></div>
        </div>
        <div>
            <div>
                <div></div>
                <div></div>
            </div>
            <div></div>
        </div>
        <div></div>
    </div>
</div>

The way the code works is you recursively call a function that looks at all the children nodes of a node. Then you pass the children to the same function. You check to see if the node you are on has no more children and when that’s true you know you have reached the bottom of a branch in your markup tree. In my example I was using jQuery.children() but the base DOM has a similar ChildNodes function.

function ShowLowestDivStyle(parent) {
    var children = parent.children();

    if (children.length > 0) {
        children.each(function (index) {
            ShowLowestDivStyle($(children[index]));
        });
    }
    else {
        //This branch lets us use the last node
        parent.text(parent.attr('class'));
    }
}

However afterward I wanted to see if I could do the same thing with a closed from solution. My idea is to create a loop where each time we take a list of current nodes and check if they have children. If not we perform some sort of action on them. Else we get rid of our current node list and then promote our list of children to current nodes. This loop would walk down a tree one level of depth at a time.

function WorkingWithChildren(rootNode){
    var depth = 0;
    var currentNodes = $();

    currentNodes = rootNode.children('div');

    //Find all the end nodes in each branch
    while (currentNodes.length > 0) {
        //Get the next set of child nodes
        var nextNodes = currentNodes.children('div');

        //Perform actions on childless nodes
        currentNodes.each(function () {
            //Convert DOM node to jQuery node
            var jNode = $(this);
            if(jNode.children('div').length == 0){
                jNode.text(depth);
                jNode.attr('style', 'margin-left:' + depth + '0px;');
            }
        });

        //Update the list of current nodes
        currentNodes = nextNodes;
        depth++;
    }
}

If you run the script you should see each div gets indented by its level of depth and contains its level in the tree.

Looking at JavaScript Hash as a Case Alternitive

I had to do a mapping today and used the hash properties of objects in JavaScript to take care of it.

function a(key) {
    var myHash = {
        'valueOne':'mapedToA',
        'valueTwo':'mapedToB',
        'valueThree':'mapedToC',
    };

    return myHash[key];
}

Later on someone asked me about a similar issue they were trying to solve in their own code and I noticed they were using a case statement for the same type of thing.

function b(key) {
    var retVal = '';
    switch(key){
        case 'valueOne':
            retVal = 'mapedToA';
            break;
        case 'valueTwo':
            retVal =  'mapedToB';
            break;
        case 'valueThree':
            retVal =  'mapedToC';
            break;
        default:
            retVal = undefined;
            break;
    }

    return retVal;
}

Now, of course, I like my code better. However in this case the hash is cleaner. Seeing my hash in place of a case statement got me thinking of the switch / case pattern. In this example the hash and the case are interchangeable. So I started thinking of how in JavaScript with functions as objects, a hash could perform in the same way as the a switch / case.

Look at this case pattern:

function c(key) {
    switch(key){
        case 'valueOne':
            //do some work because it valueOne
            break;
        case 'valueTwo':
            //do some other work because it valueTwo
            break;
        default:
            //Cover our corner cases
            break;
    }

    return retVal;
}

Using lambdas we could do something similar with a hash:

function d(key) {
    var myHash = {
        'valueOne': function {
            //do some work because it valueOne
        },
        'valueTwo': function {
            //do some work because it valueTwo
        }
    };

    myHash[key]();
}

Now though initially when I had the idea it was quite exciting. In implementation it ends up having very similar layout and syntax to the case statement. The additional thing to notice is that when using the hash there is no default action if the value is not in the hash. When passing in a value not in our hash, an exception is thrown that the function with the name of the missing value is not defined. However it’s not much code to take care of that issue as well.

function e(key) {
    var myHash = {
        'valueOne': function() {
            //do some work because it valueOne
            alert('mapedToA');
        },
        'valueTwo': function() {
            //do some work because it valueOne
            alert('mapedToB');
        }
    };

    myHash.hasOwnProperty(key) ?
        myHash[key](): //Have key, carry on
        (function() {  //Else cover our bums
            //Cover the corner case
        })();
}

The fix is to check if the object has that property then we can execute an alternative function to cover that case. Could this have been done with an if / else instead of an ternary statement. Yeah, but the point of this exercise was to experiment with the application of functions as objects. So as soon as we define it we execute it.

With this pattern we ‘could’ use the hash in place of the case. By now we can see that the syntax of a case is much more appropriate and concise for anything beyond a simple mapping. It’s things like this that I like to explore and be creative with in JavaScript.

Arduino Powered 3×8 LED Text Scroller

Where did this project come from?

I bought a chain of LEDs a while ago to make a POV light display in a bicycle wheel. There are many other bike wheel POV projects but they are one color per POV unit. I wanted to make a full color POV display for a bike race I was going to do with my family. We ended up not signing up for the biking event, and as such I never ordered the hall effect sensor for the POV display so I had some extra parts that needed to be purposed. So I decided I would make a 3 by 8 text scroller. It would take strings of characters and scroll very low fidelity versions of them across a 3 by 8 matrix of colored leds and then loop back to the beginning.

Hardware

The hardware setup was fairly simple. I was using an old PC power supply to power the Arduino board and the LEDs. From what I had read the lights could pull 2 amps when at full illumination and the board would pull .5 amps with full PWM both at 5 volts. The max power for the project would be 12.5 watts and with the power supply handling up to 35 I was covered. Unfortunately for this project I never hooked up my Digital Multi Meter to test what the actual usage was. I was running the boards PWM at half rate and the color values I used for the LEDs were also at the lower threshold of their ability because of how bright each one of them was. The one of the nice things about PC power supplies for the an electronics hobbiest is that the older connectors will have a 5 volt wire a 12 volt wire and two grounds. The down side is they have a much higher electrical output potential than a USB cable or battery so you need to be less dumb around them. Combine with that a switch to turn the power supply on and off when needed and they make a good bench power source.

Hooking up the LEDs I used the diagram off of the Adafruit Site that had a very basic wiring diagram and a wrapper library for the lights. I packed the lights into a grid of 3 by 8 plus one on the end. they started at the bottom left and each column started back at the bottom and was added to the right of the one before it. I had made a 5 by 5 grid for a proof of concept I had done before and used hanger wire to hold the lights together. In this case I just used scotch tape for each 3 by 1 column and then taped them all tougher in the end. You may notice a little bowing in the grid and that’s because it was not reinforced.

Putting Together the Software

The programming part of this project was much easier for me. I had continued to have exposure to C++ after college and Wiring, one of the the development platforms for the Arduino, is the nearly the same thing with some minor differences. The challenge with the software was in solving a couple distinct issues. was in in deciding how to represent the characters of the font.

  1. How would each character be represented in data?
  2. How would I store the string for the LEDs?
  3. Based on that how would each character be added to the message?
  4. How would I update the display with new character data as it scrolled?

If you want to skip the explanation check the source out.

Working out a Font

Starting the the characters I would have to come up with a really low fidelity font containing each character I would want to display. My initial idea was to get all the characters to fit into a 3 by 3 grid. This would be easy enough to try. In doing so I ended up finding that using a lower case approximation was a little less ambiguous that most of the upper case alternatives. The fonts ended up looking like the ones below.

A       B X    C XXX   D  X    E XXX   F XXX
  XX      XX     X        XX     XX      XX
  XXX     XX     XXX      XX     XXX     X

Some characters were just hard to work with like E and F and M. One thing about the fonts were that they were 9 bits for a 3 by 3 grid. there are 8 bits in a byte so I would end up having to use 16 bits at a minimum for each character. Thinking of this I realized that the grid for my font was actually 3 by 5. This helped out when trying to render some characters like M.

M
  XXXXX
  X X X

Storing the Grid Data and Writing it to the LEDs

The easiest way to store the data for the scroller would be to use a character string. When scrolling as each character was needed I could add it to the buffer for the LEDs. Though the LEDs are capable of 15 bit color for this project they would be set to just one. Thinking singularly I used bits. The other advantage to this is that to move or scroll the data along the grid I could just use a bit shift. That worked out well considering that the way the LEDs work was to push each character out to the end of the light chain one by one. this meant I could loop though the number of lights in the grid and write each bit to a LED of the grid to an LED.

  for(int i = 0; i < cStripLen; i++){
    if((lights >> i) & 1) {
      strip.setPixelColor(i, Color(lightValue,lightValue,lightValue));
    }
    else {
      strip.setPixelColor(i, Color(0,0,0));
    }

Now going from character in a string to the correct character from the font and then adding was a little involved so I’ll cover that after I talk about how the font data was encoded.

The Font as Data

Knowing more about how I would store the grid data encoding the fonts was now doable. If the low bits in the grid would be shifted down to scroll that would mean the new font data would be put in the high end of the grid bits. they would enter the grid at the right and scroll left. This would mean that the left side of the font would have to be put in first. Given those two issues if I wanted to move that font data in 3 bit “columns” I would have to encode that into the font memory first and the later columns would have to be packed in higher in the long that would hold them. With all that I though of some ways of using unions and structs with bit fields to make encoding this easier. However as I backed in the first few characters as test data I found it was much easier to convert the font to binary and encode it as hex that use the unions and structures. Some time I should still try to do that.

Here is a basic example of how the fonts got encoded. Well start by looking at U. To keep the left side of the font in the low order bits we have to start in the lower left of the character and encode it from bottom to top, then move to the next column and repeat. This produced the binary data that would be stored and used as the font. For assignment I converted it to hex;

U      Becomes 000  Column 1: 0 <-- Bit 2 Column 2: 0 <-- Bit 5
  X X          101            1 <-- Bit 1           1 <-- Bit 4
  XXX          111            1 <-- Bit 0           1 <-- Bit 3

Using this pattern the character in binary would be written as:
Bit Position:    4    0
       Value: 1100 1011
      As Hex: CB
//The final character encoding ended up looking like this:
//Setup values for pixel characters
  //Numbers
  pixelChars[0] = 0x1EF;
  pixelChars[1] = 0x7;
  pixelChars[2] = 0x7C;
  pixelChars[3] = 0x1FD;
  //...

  //Characters (+10)
  pixelChars[10] = 0x5B; //a
  pixelChars[11] = 0x1F; //b
  pixelChars[12] = 0x16F; //c
  pixelChars[13] = 0x3B; //d
  pixelChars[14] = 0x17F; //e
  pixelChars[15] = 0x137; //f
  //...

  //Special Chars
  pixelChars[36] = 0x0; //space
  pixelChars[37] = 0x12; //-
  pixelChars[38] = 0x1; //.
  pixelChars[39] = 0x5; //:
  pixelChars[39] = 0x4; //'

Driving the Text on the Grid

So writing the text is fairly simple in concept. So as the grid moves the values for the buffer down they have to be replaced. The next character in the string we want to show should be pulled and written to the buffer. The text in the string we want to display needs to be mapped to the appropriate character in our font. We also have to know where we are in the columns in the font so we can write the correct values to refill the buffer. Finally it would be good to put space in between each character as we print them. Each one of these steps needs to be keep track of while the values in the buffer shift and gets replaced column by column.

void CharacterShifter() {
  //shift lights 3 pixels lower
  lights = lights >> 3;

  //if the pixelCharIndex is at the end (maxPixelCharIndex) then
  //get a new character from the buffer
  if(pixelCharIndex >= maxPixelCharIndex)
  {
    // set the pixelCharIndex to 0 and move to the next char
    pixelCharIndex = 0;
    stringIndex++;

    //then pull the next character from the buffer
    if(textToScroll[stringIndex] == '\0')
    {
      //if the value in the buffer is null then set the position
      //of the buffer to zero
      stringIndex = 0;
    }

    //Since we are changing characters in the buffer insert a one pixel space
    //Which was already done for use when we shifted our bits down 3
  }
  else {
    //print the 3 bits of the value indexed in the buffer
    unsigned int pixelChar = CharToPixelChar(textToScroll[stringIndex]);
    lights = (((unsigned long)(pixelChar >> (3 * pixelCharIndex) & 0x7))
                 << (3 * 7))
                | lights;

    pixelCharIndex++;

    if(pixelCharIndex < maxPixelCharIndex &&
        (((pixelChar >> (pixelCharIndex * 3)) && 0x7) == 0))
    {
      pixelCharIndex = maxPixelCharIndex;
    }
  }
  //print the first 3 bits of the value indexed in the buffer
  //increase the pixelCharIndex
  //if maxPixelCharIndex is less than 3 check next three bits
  //if they are equal to zero set the index to maxPixelCharIndex
}

You can see how with each shift how each part of the process is moderated and managed. Now how the font was retrieved was fairly simple as this next snipet shows. With some input checking the array that stores the font can be used as a basic look up table.

unsigned int CharToPixelChar(char c){

  byte index = 0;

  if('0' <= c && c <= '9') index = c - '0';
  else if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')){
    if('a' <= c && c <= 'z') index = c - 'a';
    else index = c - 'A';
    index = index + 10;
  }
  else if ((byte)c == (byte)' ') index = (byte)36;
  else if ((byte)c == (byte)'-') index = (byte)37;
  else if ((byte)c == (byte)'.') index = (byte)38;
  else if ((byte)c == (byte)':') index = (byte)39;

  return pixelChars[index];
}

And finally a video of the result: “This was a triumph – I’m making a note here: HUGE SUCCESS. The LED Scroller is not a lie.”

Demo of a 3×8 LED Text Scroller

One of my personal projects was to make a radial POV display to use on a bike ride my I was going to do.  Well… the project was put off after my move and later I decided not to do the ride. However, I came across the board and lights with a new idea. I could take the 25 lights and turn them into a 3×8 scrolling text grid. What could be complicated about that? Right?

I will have a full right up on the design, code, and issues I ran into when desiging the project but untill then I’m just going to post what I consider stage gate 2 of 3 for the project. Scrolling numbers.

When to use lamdas in your code

I like new features in programming languages that enable more flexibility or encompass features for a frequently used patter. A good example is foreach. This was a basic pattern that eventually was incorporated into the syntax of many languages. That being said, I am cautious of change for the sake of it.

Some nice things about C# 3 and .Net 3.5 are LinQ and lambdas. LinQ moves C# and .Net toward extending array objects in what I believe is their next natural abstraction, collections, and providing the tools to effectively manipulate them. I have used lambdas for simple delegates and in a testing pattern I was using with threads. However almost all of the time when I try to re-factor code into a lambda I end up asking why not just make this a function call?

The Case Against Lambdas when not filling in LinQ parameters.

I come across primarily two arguments when talking about lambdas and debating their use in code.

One is that they don’t end up saving any space v.s. refactoring to a separate function. If you count line by line you can usually save a static one or two lines which in the grand scheme is not very significant.
Also the other disadvantage is that they don’t exist outside the scope of where they are declared. A separate function would and could have access modifiers applied like Private, Public, or Protected applied to control is visibility even more.

Another issue is that some programmers are not used to reading code with lambdas in it. They don’t understand their scoping and the object lifetime issues they could complicate. With this argument I like to try and imagine it being used when foreach was added to the language. Honestly this can be said about a lot of features of C# including the using statement.

The case for Lambdas

I am a really big fan of don’t repeat your self. So I frequently refactor code if the same logic or lines shows up two or more times. When the logical scope of the code is extremely local, I think lambda. Other wise it would qualify for being factored into a function. One pattern I have used is when there is a logical section inside is also performed either once before or after the loop.

//Logic before loop
localtemp = source.GetSomeValue();
localCollection.Add((localTemp + anotherLocalVar) / yetAnotherLocal);

while(source.IsActive)
{
	//Keep looping till no longer active
	localtemp = source.GetSomeValue();
	localCollection.Add((localTemp + anotherLocalVar) / yetAnotherLocal);
}

We have two approaches to this. One would be to re-factor it to a function that would be local to the code, probably protected or private in the same class. The other option is to use Action() to make it a lambda. Lets look at both starting with moving the code to a function.

private void RefactoredActions(object source, object collection, object extra, object divider)
{
	object localtemp = source.GetSomeValue();
	localCollection.Add((localTemp + extra) / divider);
}

// ... ... ... ...

//Logic before loop
RefactoredActions(source, localCollection, anotherLocalVar, yetAnotherLocal);

while(source.IsActive)
{
	//Keep looping till no longer active
	RefactoredActions(source, localCollection, anotherLocalVar, yetAnotherLocal);
}

This would work but the number of parameters can get quite large if there is a lot of interaction in the loop logic with other locally scoped variables. The code is now located in one place and any updates to the logic can be done once with out injecting any bugs.
Now lets look at it using Action().

//Logic before loop
Action loopLogic = () =>
{
	object localtemp = source.GetSomeValue();
	localCollection.Add((localTemp + anotherLocalVar) / yetAnotherLocal);
}
loopLogic();

while(source.IsActive)
{
	//Keep looping till no longer active
	loopLogic();
}

This is where a Action() can end up refactoring the code into a concise call. This works because everything in the lambda exists in the in scope local to the loop. The syntax can be much cleaner and scope of understanding various parts of the code is reduced.

Conclusion

Though personally the cases where I have adopted lambdas are small. They can be useful in your code. New paradigms should not be adopter or shunned because they are simply new. They should be used based on their features and function. This is one case where I have found lambdas have helped and I hope you find it useful and welcome you comments and understandings.

The State of our Patent System

This American Life did a show on the patent system in the US and it’s quite jarring. It’s crazy how no one will comment on the patent troll in the story out of fear or reprisal. Wish washington would do something about it but with the way things are going this week I’m not exactly confident that would ever happen.

http://www.thisamericanlife.org/radio-archives/episode/441/when-patents-attack