Why I Love C# More Than I Care About Ruby

@robconnery I’m really glad that you are excited. I think anytime someone is healthily and safely passionate about something, it can only be a good thing.

Rob has a great post where he lists 4 cases where he likes Ruby and compares to the same thing in C#. Case 1 Expressiveness: Rob likes the unless statement and the post expression if statement. Case 2: Rob likes Gems. Case 3: Rob likes simple things. Case 4: Rob likes sending messages, open classes and method missing.

Python and Perl already did all this, so why Ruby?

Case 1 and 3 were true in python when i started writing it in 1996 and case 1, 2 and 3 were true in perl when i started writing it in 2000. I’m sure case4 is true in both python and perl too, but I never went that deep into either of them. Much like in Ruby, you don’t have to go that deep to get things done.

I am of the opinion that if you have never seen a dynamic typed language before, or maybe a dynamic typed language other that BASIC or VB before, that Ruby has all of the appeal which you tout. However, there are some of us who write C# because we actually like it, we write desktop applications, and find it to be the best static and strong typed language around. We came to C# and were super impressed because the weak typing of C wasn’t there. The rough edges of C++ wasn’t there and for nearly all applications there is no performance difference and sometimes the GC and managed environment actually gives a boost in performance over some of the bad C++ we were writing before.

So should someone who has never written in Perl, Python, Pike and PHP go try out Ruby… absolutely… get the exposure.

Alternatively, if you have done some Perl or Python and now you are a C# guy. Ruby might not seem so impressive. In fact, it looks more like the same thing with a new coat. I can’t tell what the hype is about. There isn’t much new and different.

All that said, after years of Perl, learning C# was a challenge, especially since I was using it to solve many of the same problems for which I had been using Perl. WHY? was I doing it that way? Well I wanted Windows Forms UI front ends on my Perl versions of programs there were ultimately just sed/awk/grep and some ldapsearch/ldapadd/ldapmodify commands. Not commands really, but calls to libraries.

There is a good reason that the “simple things” aren’t AS simple.

What I learned was that there is a damned good reason that Case 3 “The Simple Things” were a little more complex in C#. The separation of stream and textreader abstract types in C# make huge sense once you realize that doing the same thing in perl or python (or ruby) can be a bit of a hassle. The organization of decorator streams in the .NET BCL just makes sense. Want to compress? Decorate with the stream compressing class. Want to encrypted? Decorate with the stream encrypting class. Want to do both? In either order? Decorate appropriately.

I do share Rob’s opinion. It is a little prettier in Ruby. I’ve already gone on record as saying that “var” in C# should be optional. In VB6 the Let statement was optional. In VB.NET the Let statement is no supported. IMO C#’s var isn’t much different than VB.NET’s Let and Dim. Sure would be nice if it were optional.

I’ve also requested static imports so that we could do things like just call the open method instead of saying File.Open. When you are in a nice tiny singly responsible file, it just makes sense.

These things don’t change my ability to write code.

On .NET’s lack of a CPAN, Cheeseshop, Gem equivalent: YES! YES! YES WE NEED IT NOW!

I can’t say anything other than .net needs CNAN (comprehensive .net archive network) or maybe CCAN (comprehensive CIL archive network). I can’t decide which name I like better.

As for metaprogramming, I think that Python, Perl and Ruby’s ability for runtime metaprogramming will continue to be far beyond anything you see in the C# world. That is not say that metaprogramming is not possible in C#. Its just very different. Its typically compile time metaprogramming. Thanks to the addition of T4 in VS2008 and 2010, metaprogramming in C# is readily available and powerful.

I could go on and insert above about how I learned to love the .NET RegularExpression API after having it blow my mind in comparison to perl’s. Or about how poorly documented the System.DirectoryServices API is, but that once I got it I loved it so much more than Net::LDAP. Or about the extreme pain in building CPAN modules on a Sun Sparc and how installing Mono and using Visual Studio and C# was actually easier than making Perl work properly.

But rather than elaborate on those things, I’ll end by saying, yes, Ruby is awesome, if you have never seen any of the things which make it awesome before.

C# 4 Optional Parameters Limits Default Value

Jon Skeet has an excellent C# 5 talk video from the recent Norwegian Developer Conference. Go watch it.

When he showed Default<T>, I immediately thought it was just an variation of Option<T> or F#’s option type, but with added default value logic. Its cool.

He was asking for compiler support so that things like this would be possible.

Default<int> a = 1;

Well, I thought, you don’t need compiler support for that, just add an implicit type converter to your definition of Default<T>

        public static implicit operator Default<T>(T value)
        {
            return new Default<T>(value);
        }

No worries, right?

Oh I was so wrong. While this will work for the regular above statement, it won’t work as a default parameter value.

     class Things { public Things(Default<int> a = 5) { } }

This provides a wonderfully descriptive error (I love this compiler) which says “a value of type ‘int’ cannot be used as a default parameter because there are no standard conversions to the type ‘Default<int>’”

Now I’m crying? Why the limit? Instead of Jon’s request for awesome Default<T> support in C# 5, I request considering implicit type converters on optional parameter default values.

Teaching New Programmers

I teach at a local community college. This semester I’m teaching one of a handful of sections called “Introduction to Computer Science”. This course is supposed to be a bridge course before throwing new students directly into the typical C++ Programming course.

The thought is that some students need a little extra help before taking that first C++ course. This course is intended to give them some intermediate information and some very basic programming introduction.

Since there are other sections to this course I’ve not had to make my own course material. I’ve used PowerPoint created by others. A few times I’ve had to say things like “Just ignore that bullet, its only true from a certain point of view.”

It wasn’t until the introductory C++ slides that I blew a gasket.

After a slide on “Documentation” with these bullets:

•A well-documented program is easier to understand and modify
•You use comments to document programs
•Comments should appear in a program to:
?Explain the purpose of the program
?Identify who wrote it
?Explain the purpose of particular statements

I advanced to this slide with an example of “good” comments:

int feet; //variable to hold given feet
int inches; //variable to hold given inches
int totalInches; //variable to hold total inches
double centimeters; //variable to hold length in centimeters

At this point I lost my professionalism a bit and cursed quite a lot. I ranted about how this was useless. I feel like a channeled a little bit of everyone who I’ve heard say “comments are evil”.

When I finally got to a complete demo program instead of a code snippet, It was time for conniption.

//named constants
const int CENTIMETERS_PER_INCH = 2.54;

int main() {
  //declare variables
  int feet, inches;
  …
  // statements
  …

For the love of programming will someone explain to me what value any of these comments have?

I can only hope that my ranting was not so extreme that students stopped listening. Hopefully they will all have a better understanding of comments and what NOT to do.

LINQ Abuse with the C# 4 dynamic type

With C# 4 adding some support for dynamic typing one of the first thing that I wanted to do is use it with LINQ.

I want to do this:

dynamic x;
var h = from y in x where y == 1 select y.something;

But I get error messages on both where and select that says

Query expressions over source type ‘dynamic’ or with a join sequence of ‘dynamic’ are not allowed

Major bummer.

But surely there is something I can do. 🙂

*the title of this post starts with LINQ abuse… please don’t comment about how stupid and evil this is. I know it. Instead, consider this an exercise in getting to know C# a little better.

The dynamic type is just sugar for the object type and some attributes to which the compiler pays attention.

Lets use object…

object things = new[] { 0,1,2,3,4,5,6,7, };
var whatIwant = from thing in things
                            where thing % 2 == 0
                            select thing;
// or if you like longhand:
var wiw = things.Where(thing => thing%2 == 0).Select(thing => thing);

How does this compile? Well, by making Where and Select resolve to extension methods on object instead of extension methods on IEnumerable<T> (which is what people USUALLY think of when they think LINQ).

public static IEnumerable<dynamic> Select(this object source, Func<dynamic, dynamic> map)
{
    foreach (dynamic item in source as dynamic)
    {
        yield return map(item);
    }
}
public static IEnumerable<dynamic> Where(this object source, Func<dynamic, dynamic> predicate)
{
    foreach (dynamic item in source as dynamic)
    {
        if (predicate(item))
            yield return item;
    }
}

Extension methods on object, then cast to dynamic (extension methods aren’t allowed on dynamic).

It should be short work to fill out whatever LINQ methods are necessary to make whatever LINQ expressions you wish work against dynamic (object) and now you can use LINQ with a source that is typed dynamic.

double.IsNaN is 100 times slower

Its not just your programming group that can’t get it right. I work in a semi-disfunctional group on contract for a client who, not matter how hard we try, doesn’t seem to listen to basic software engineering principles.

I feel a little better (and a great deal worse after thinking about it) when I see that the largest software company in the world deals with some of the same problems.

I found this gem in the WPFToolkit (it is MSPL) source.

// The standard CLR double.IsNaN() function is approximately 100 times slower than our own wrapper,
// so please make sure to use DoubleUtil.IsNaN() in performance sensitive code.
// PS item that tracks the CLR improvement is DevDiv Schedule : 26916.
// IEEE 754 : If the argument is any value in the range 0x7ff0000000000001L through 0x7fffffffffffffffL
// or in the range 0xfff0000000000001L through 0xffffffffffffffffL, the result will be NaN.        
public static bool IsNaN(double value)
{
    NanUnion t = new NanUnion();
    t.DoubleValue = value;

    ulong exp = t.UintValue & 0xfff0000000000000;
    ulong man = t.UintValue & 0x000fffffffffffff;
    return (exp == 0x7ff0000000000000 || exp == 0xfff0000000000000) && (man != 0);
}

 

My jaw was open pretty far for quite a few seconds as I read this.

I’m Lazy And I Need My Helpers

public static class NumericExtensions
{
public static bool IsZero(this byte number)
{
return 0==number;
}
public static bool IsZero(this short number)
{
return 0==number;
}
public static bool IsZero(this int number)
{
return 0==number;
}
public static bool IsZero(this long number)
{
return 0==number;
}
public static bool IsZero(this float number)
{
return 0==number;
}
public static bool IsZero(this double number)
{
return 0==number;
}
public static bool IsZero(this decimal number)
{
return 0==number;
}
}

I wanted something like this today as I was toggling between NUnit and MSTest. Sure, Assert.That( something, Is(0) ) is readable, but its not portable. Its NUnit only, and for this project, I can’t do that. I also like the english reading of IsZero() vs. Is(0)

I think I’ve stated before that any code on this blog (c) by me and licensed under the MIT/X11 License, but for certain bits of code, I see no point in that. So I’m going to start tagging code with CC0, Unlicense and/or WTFPL.