Language Readability vs. Writability
In my previous post, I said:
“Unfortunately, language readability is often at odds with writability.”
And
“Generic method type parameters are inferred from the concrete parameters”
Here’s what I’m talking about:
T F<T>(T t) { return t; }
void Test()
{
Console.WriteLine(F(1) + 2);
}
Which overload of Console.WriteLine gets called?
The compiler sees that you’re passing ‘1’ to F(), which is an int. So, the concrete parameter ‘t’ is an int, so the type parameter ‘T’ is an int, so F() returns an int. Add an int to ‘2’ and you get an int. So, we are calling
public static void WriteLine(int value);
I don’t think that’s immediately obvious from the code, but it sure is easier to write than:
Console.WriteLine(F<int>(1) + 2);
The other inference added in C# 2.0 is with delegates. Consider:
delegate void D();
void F() { }
void Test()
{
D d = F;
d();
}
It’s certainly easier to write than:
D d = new D(F);
But because it’s inferred, it’s harder to read, both for tools & for devs.
The final point was about ‘foreach’. Today you write:
void Test(List<int> myList)
{
foreach (int i in myList) { }
}
But why not let you write:
void Test(List<int> myList)
{
foreach (i in myList) { }
}
Can’t the compiler figure out the type of ‘i' for you? Yes, but now you’ve compromised readability:
foreach (i in foo.bar(baz(x))) { }
Now, to know the type of ‘i', you have to correctly figure out which overload of ‘bar’ is called, which requires figuring out the correct overload of ‘baz’, too. It could be quite complicated.
Since I’m on the editor team, I think solution lies in an editor. When making a decision about read vs. write, one option is to select easy-to-read, and then use the editor to make it easy to write. For example, a smart editor could infer & insert the type in the ‘foreach’ for you automatically.
Hmm, guess I need to get to work!