Wednesday, November 28, 2007

Quick Tip - Read Only Automatic Properties

This is a simple little trick, which I only discovered a few weeks ago.

In the past providing public "read only" access to a member would look something like:
private string connection;

public string Connection
{
get { return connection; }
}

With Automatic Properties in C# 3.5 the code becomes:
public string Connection { get; private set; }

The neat trick is the access modifier (private) next to the set. This allow you to internally modify the member, while publicly providing "read only" access.

Monday, November 26, 2007

VS2008 RTM Update

I have updated all the downloadable code to compile with the RTM release of VS2008.

It's not a big change, so I'll use this blog entry to update my Xceed <-> Linq code. I've fixed some minor bugs, improved performance a lot and added better linq syntax support.

So if you're using the code, it'd be a good idea to update.

Monday, November 19, 2007

IEnumerable Joy - Batch / Split

I was inspired by my good friend Nick's latest blog entry Return of the Batch Enumerable

Here he demonstrates a neat idea of using extension methods and yield to split an IEnumerable into arbitrary batches.

My version is slightly less efficient, but treats the batches as separate lazy collections - so you can use it on multiple threads etc.

I've also added a Split extension, which I'll describe - but first, the code!

static class InBatchesExtension
{
public static IEnumerable<IEnumerable<T>> InBatches<T>(this IEnumerable<T> source, int batchSize)
{
for (IEnumerable<T> s = source; s.Any(); s = s.Skip(batchSize))
yield return s.Take(batchSize);
}

public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> source, int items)
{
for (int i = 0; i < items; ++i)
yield return source.Where((x, index) => (index % items) == i);
}
}

The InBatches returns the same output as Nicks:

Batch: 1 2 3
Batch: 4 5 6
Batch: 7

And the Split batches the output across the collections:

Batch: 1 4 7
Batch: 2 5
Batch: 3 6

So this gives you 2 different batch splitting methods for a generic enumerable.

I love this stuff.

Tuesday, November 13, 2007

Wield the Yield

Recently I've noticed an IO pattern emerging combining yield and linq; a powerful and efficient mechanism to read data.

Check the following code: We safely open a file (with the using statement), and yield the results with a loop.
IEnumerable<string> ReadFile(string filename)
{
using (StreamReader reader = new StreamReader(File.OpenRead(filename)))
while (reader.EndOfStream == false)
yield return reader.ReadLine();
}

This simple (and beautiful) code allows us to treat a file like an array of strings - which becomes very powerful when coupled with linq.
// Contrived example - How many file lines refer to "fred"?
var result = ReadFile("file.txt").Where(x => x.Contains("fred")).Count();

I'm sure this same pattern could also be applied to other data retrieval methods, eg algorithm calculation (prime numbers, Fibonacci, etc), network communication (message queue) and even as an abstraction over asynchronous data methods.

Yield provides a lazy enumeration (doesn't execute unless needed) so the solution is generic and efficient - I like it.

Monday, November 5, 2007

n! - let me count the ways

The other day I had an interesting discrete maths assignment question involving permutations - so I decided to codify it.

"How many ways can six people (Josh, Toby, CJ, Sam, Leo & Donna) sit, if Josh must sit to the left of Leo and to the right of Sam."

Now the astute reader will immediately recognize the answer to be 2 * (4! + 3!3!) = 120; but to be sure I wanted to double check this via C#. (I'm keen to redo this in F# too)

My solution was a quick hack, and is by no means "the best way" - but using linq it sure looks pretty.

class Program
{
static IEnumerable<List<string>> Permutate(IEnumerable<string> people,
IEnumerable<string> current)
{
// Get remaining people and recurse
foreach (var person in people.Where(x => current.Contains(x) == false))
foreach (var result in Permutate(people, current.Concat(new string[] { person })))
yield return result;

if (current.Count() == people.Count())
yield return current.ToList();
}

static void Main(string[] args)
{
string[] people = new string[] { "Josh", "Toby", "CJ", "Sam", "Leo", "Donna" };

var result = Permutate(people, new string[] { }).ToList();

// Josh sits to the left of Leo
var Josh_Leo = result.Where(r =>
r.FindIndex(x => x == "Josh") < r.FindIndex(x => x == "Leo"));

// Josh sits to the right of Sam
var Sam_Josh = Josh_Leo.Where(r =>
r.FindIndex(x => x == "Sam") < r.FindIndex(x => x == "Josh"));

var count = Sam_Josh.Count();
}
}

This simple example shows why I'm a such fan of linq in C# - the pre-linq code for this certainly wouldn't be as eloquent.

Oh, and it also shows why I'm a fan of maths... it's much more efficient to just to calculate the factorials.

Update: Formatting code in a blog sure is a pain!

Tuesday, October 30, 2007

F# is so Passé

Lately I've been trying to juggle learning a mix of technology. WPF, .net 3.5 (linq), maths, F#... Sometimes I feel like I have Internet Multitasking Syndrome.

Although Internet Multitasking Syndrome is not a known medical disorder (I just made it up five minutes ago), it is not uncommon for people to become so immersed in their online activities that their cognitive abilities wane.

After hours starring at a screen, flipping between web pages and information outlets, people can develop a feeling of anxiety, stress and a decrease in mental performance, said John Suler, author of The Psychology of Cyberspace.

"There are limits to how much information one person can process," he continued.


I started learning about a little known language called F# a couple of months ago, where I read most of the Foundations of F# book over a rather intense week.

Since then I've dropped the ball... there's just too much to learn within our software field.

I'm keen to get back into it, as F#'s functional principles are very appealing to me. There's a sense of power and elitism playing with such a language. It's close to it's mathematical roots, and has the potential to create highly concurrent systems.

These things are addictive for software engineers. Power and elitism - it's why C/C++ are so popular and why VB programmers get no respect.


Now that F# is an official MS language, it's becoming quite popular. While this is fantastic for the language - a small selfish part of me wants to keep it for myself. I don't want it to become 'common' and spoilt by countless bad programmers writing spaghetti code.

Unfortunately this also includes me - so to avoid becoming an Italian Chef, I'm planning to read Structure and Interpretation of Computer Programs during my holidays. I've heard this is a classic book covering functional programming (in scheme).

Wish me luck!

Wednesday, October 10, 2007

Death Trap

When I first started riding my motorbike I became much more aware of my environment... and not in a pleasant way. After coming out of my metal cocoon (car), everything became a threat and I felt fully exposed to the world.

It's with good reason too; I live in beautiful Queensland where every week 1 rider dies and 15 are injured. And I don't need a maths degree to know that the statistics are against me.

Even still I love riding my bike, it got me out of my comfort zone and I have a new perspective, and a new sense of freedom and opportunity.

So here comes the clichéd analogy to programming.... Our comfort zone is our greatest death trap.

Our industry moves far too quickly learn everything, so it's an easy trap to become stagnant with familiar technology.

We've all been victim's of stagnancy at some point, but tragically some developers spiral down until they feel so far behind there's no point playing catch up.

Then they're stuck working with an obscure, unsupported technology - or they get promoted into management.

Others are trapped by their language of choice. I met a guy just recently who, with great passion, thought 'C' was the language for everything. Web apps, database apps... everything.

I felt for this guy, because I've been there before... and it's utter madness.


It takes effort and it's painful to learn new things. There's also a high risk that what you learn is completely redundant... but while it's important to pick your technology carefully - it's better to learn something than nothing at all.

My challenge is to never stop learning; it's not without risk or effort - but the rewards of freedom and perspective are invaluable.