Fun with C# and Node.js

A co-worker was looking for a nodejs module to generate UUIDs the other day, and it inspired me to write one that leverages C# to generate guids.  I wrote a simple C# class and compiled it with Mono as an executable.  It takes a single argument which is the number of guids to generate.  This executable is executed with the ‘child_process’ module that comes packaged with node, and receives its arguments from my node module.  The console output is then read and parsed, and returned to the calling JavaScript code.

I am definitely interested in further exploring a possible bridge for C# mono assemblies in node.  It seems that others are as well.

LINQPad sponsors STL ALT.NET

LINQPadI remember when LINQ was the new hotness.  When developers realized that they could stop writing `for` and `foreach` loops to farm data from collections.  It was a magical time, full of unicorns and rainbows and such.  In this midst of this bliss Joseph Albahari, author of the excellent C# in a Nutshell, released a small program called LINQPad that functioned as both a pseudo-C# LINQ REPL and a light-weight frontend to SQL Server (via LINQ2SQL).  Using LINQPad was (and still is) a great way to explore the LINQ API without breaking actual production code.

Since those early days, LINQPad has grown to support all of the major LINQ technologies and other data providers, including:

  • Entity Framework
  • LINQ to XML
  • Parallel LINQ
  • OData
  • WCF Data Services
  • SQL Azure
  • and many more!

In addition, LINQPad can also serve as an F# REPL, for those of the functional persuasion who would like more flexibility than FSI provides.

LINQPad is also extensible.  When I worked with Josh Buedel, he created a plugin for LINQPad that queried an XML web service exposed by an online billing provider that we were using at the time.  Using LINQPad, we could write LINQ queries against the service endpoints as if they were object collections, which made debugging service issues and generating ad hoc reports a breeze.

While LINQPad has always been free, users who wanted auto-completion, Reflector integration, smart tags, code snippets, etc. paid a premium fee for the Pro version of LINQPad.  Mr. Albahari has generously donated two Pro licenses to STL ALT .NET, which will be raffled to members in the coming months.  Two lucky winners will walk away with great software that no .NET developer should be without!

Naming interfaces

Interfaces in .NET have a specific naming convention.  They begin with a capital “I”, followed by some text that indicates what the interface represents.  IEnumerable is a classic example; it means the implementing object can be enumerated.  This naming convention, however, is pretty unique to .NET.  In the Java world, interfaces do not have a special prefix to indicate that they are interfaces.  Java, unlike .NET, uses two keywords, “extends” and “implements”, to indicate whether a class is participating in an inheritance hierarchy and/or representing some behavior, respectively.  In .NET, we use a simple colon and rely on the ordinal position of the class/interface names that come after to indicate the same.

The prefix “I” used for interfaces is seen by many (myself included) as unnecessary.  It serves no useful purpose other than to provide a visual cues to developers, allowing them to identify interfaces quickly while coding.  Java IDEs typically provide these visual cues so that developers don’t have to rely on a naming convention for this purpose.

Eclipse example 1

Eclipse example 2

Visual Studio has visual aids as well, but they are not as obvious, in my opinion.

I do think a naming convention for interfaces is still a good idea, but I don’t think the prefix “I” is necessary.  Instead, I would like to propose that interfaces be named for the behavior that the represent, starting with a prefix like “Can”, or “Will”, or “Has”, followed by a description of that behavior.  For example:

  • IEnumerable becomes CanEnumerate
  • IDisposable becomes CanDispose
  • IQueryable becomes CanQuery
Not only is this naming convention more descriptive and less contrived (sometimes it is difficult to come up with an interface name like IXyzable), it forces developers to really think about the behavior they are trying to implement, and may dissuade them from creating interfaces that have nothing whatsoever to do with behavior.  (The sudden explosion of IOC mania has obscured the real purpose of interfaces, but that is another topic for another time.)
If you have thoughts on this topic, I’d be interested to hear them.

Nested classes

I’ve been programming against the .NET framework for a while, and I confess that I haven’t much used nested classes.  I’ve just never had a compelling need.  But today I was working on some unit tests, and found a nice example of how nested classes can be very helpful, and even make normal classes easier to use.

It all began with DateTime.Now.  It is very hard–no, impossible–to test objects that rely on DateTime.Now in a consistent way, because you have no direct control over the value of “Now”.  It is actually an external dependency, and like all external dependencies it is best to abstract it away for testing purposes.  So I created this rather mundane interface and a simple implementation class that I could pass to any object that needed to use the value of “Now”.

internal interface ISundial {
    DateTime Now();
    DateTime Today();
}

internal class Sundial : ISundial {
    public DateTime Now() {
        return DateTime.Now;
    }

    public DateTime Today() {
        return DateTime.Today;
    }
}

I know it smacks of over-engineering, but bear with me: this is just a preamble to real content.  Anyway, so now I have a nice ISundial interface which I can use for creating a FakeSundial object in my unit test.

internal class FakeSundial : ISundial {
    private DateTime _now;

    public FakeSundial(DateTime now) {
        _now = now;
    }

    public DateTime Now() {
        return _now;
    }

    public DateTime Today() {
        return _now.Date;
    }
}

This worked great for a number of tests. I could guarantee that “Now” would be any value that I needed it to be, and then I could perform assertions to verify the results of date calculations, for example.

Some tests failed, however, and I immediately knew what was wrong.  The Now() method, by design, never advanced with the system clock, whereas DateTime.Now does.  This caused me some headaches, so I added a few convenience methods to simulate the passage of time.

internal class FakeSundial : ISundial {
    private DateTime _now;

    public FakeSundial(DateTime now) {
        _now = now;
    }

    public DateTime Now() {
        return _now;
    }

    public DateTime Today() {
        return _now.Date;
    }

    public void FastFowardSeconds(int seconds) {
        _now = _now.AddSeconds(seconds);
    }

    public void FastForwardMinutes(int minutes) {
        _now = _now.AddMinutes(minutes);
    }

    //etc.
}

This worked great and gave me the flexibility that I needed, but I still had to implement FastForwardMilliseconds(), FastForwardHours(), FastForwardDays(), FastForwardYears(), and all the damn RewindXYZ() methods that I knew I was going to need as well.  I began to alter my design a little bit. Perhaps I could just have generic FastForward() and Rewind() methods that took an int argument and some kind of enumeration to represent the various time measurements, and then build a glorious switch statement that would call the appropriate methods on the DateTime field.  But that, too, was rather kludgy, and not at all befitting for an important class such as FakeSundial.

Then I thought: wouldn’t it be nice if I could use a kind of fluent syntax to accomplish this same thing, something like:

var fakeSundial = new FakeSundial(DateTime.Now);
fakeSundial.FastForward(60).Minutes();

Two things were immediately apparent:

  1. FastForward() and Rewind() would need to return an object other than FakeSundial (otherwise, what would calling fakeSundial.Minutes() do on its own?); and
  2. that other object would need access to the private field _now in the FakeSundial instance.

The second point was the impetus for a nested type, because in C#, a class that is declared within another class has full access to the parent class’s private and protected members (much like an instance method can access the private instance variables of its declaring class).

A corollary to point #2 is that the nested class would need to be a private class, which would prevent other objects (whether children by inheritance or external to FakeSundial), from accessing the private state data of FakeSundial.  This is a good example of Encapsulation in OOP.  I decided to call this class SundialDuration:

private class SundialDuration {
    private readonly FakeSundial _fakeSundial;
    private readonly int _incrementValue;

    public SundialDuration(FakeSundial fakeSundial, int incrementValue) {
        _fakeSundial = fakeSundial;
        _incrementValue = incrementValue;
    }

    public void Seconds() {
        _fakeSundial._now = _fakeSundial._now.AddSeconds(_incrementValue);
    }

    public void Minutes() {
        _fakeSundial._now = _fakeSundial._now.AddMinutes(_incrementValue);
    }

    public void Hours() {
        _fakeSundial._now = _fakeSundial._now.AddHours(_incrementValue);
    }

    public void Days() {
        _fakeSundial._now = _fakeSundial._now.AddDays(_incrementValue);
    }
}

The class constructor takes an instance of the FakeSundial object, as well as an increment value, and performs the appropriate increment operation when the respective increment method is called. (If the increment value is a negative number, the value of “Now” will move backwards.)

The FastForward() and Rewind() methods in FakeSundial cannot have a return type of a private nested object, so I created a public interface that defined the increment methods in SundialDuration, and made it the return type of FastForward() and Rewind().  The full class implementation looks like this:

internal class FakeSundial : ISundial {
    private DateTime _now;

    public FakeSundial(DateTime now) {
        _now = now;
    }

    public DateTime Now() {
        return _now;
    }

    public DateTime Today() {
        return _now.Date;
    }

    public ISundialDuration FastForward(int howMany) {
        return new SundialDuration(this, howMany);
    }

    public ISundialDuration Rewind(int howMany) {
        return new SundialDuration(this, -howMany);
    }

    private class SundialDuration : ISundialDuration {
        private readonly FakeSundial _fakeSundial;
        private readonly int _incrementValue;

        public SundialDuration(FakeSundial fakeSundial, int incrementValue) {
            _fakeSundial = fakeSundial;
            _incrementValue = incrementValue;
        }

        public void Seconds() {
            _fakeSundial._now = _fakeSundial._now.AddSeconds(_incrementValue);
        }

        public void Minutes() {
            _fakeSundial._now = _fakeSundial._now.AddMinutes(_incrementValue);
        }

        public void Hours() {
            _fakeSundial._now = _fakeSundial._now.AddHours(_incrementValue);
        }

        public void Days() {
            _fakeSundial._now.AddDays(_incrementValue);
        }
    }

    public interface ISundialDuration {
        void Seconds();
        void Minutes();
        void Days();
        void Hours();
    }
}

Now, my unit tests can simulate the passage of time with a few method invocations:

var sundial = new FakeSundial(DateTime.Now);
var timeSensitiveObject = new TimeSensitiveObject(sundial);
timeSensitiveObject.DoSomething();
//simulate the passage of time!
sundial.FastForward(10).Days();
//operating in the future now
Assert.AreEqual(10, timeSensitiveObject.DaysElapsed);

Collection comprehension

F# (and Ruby, I am told) has a nice little syntactic feature called “comprehension” which allows developers to create lists of numbers or characters by specifying a range to be “expanded”, like this:

let numbers = [0 .. 9]
let alpha = ['A' .. 'Z']
let everyOtherNumber = [0 .. 2 .. 16]

printfn "%A" numbers // [0; 1; 2; 3; 4; 5; 6; 7; 8; 9]
printfn "%A" alpha // ['A'; 'B'; 'C'; ... 'X'; 'Y'; 'Z']
printfn "%A" everyOtherNumber // [0; 2; 4; 6; 8; 10; 12; 14; 16]

Today I’ve been working on an e-commerce project where I need to build a list of months, so I started looking for a comprehension equivalent in C# and found this less elegant but adequate (for my purposes) method on Enumerable that does something similar:

IEnumerable<Int32> months = Enumerable.Range(1, 12);

There are a few problems with Range, however:

  1. the signature is (int start, int count) instead of (int start, int end)
  2. Range only accepts and returns integers
  3. Range does not provide a means to “step” values

If anyone knows a better comprehension alternative in C#, please let me know!