Java and C# have somewhat reduced the ceremony over C++ by not requiring header files, but they are still both quite verbose. What would it look like if C# went one step further and adopted a light syntax like Python, where white space is significant?
Let’s start with an immutable Person class implemented in idiomatic C#:
namespace MyCompany.MyProduct
{
public class Person
{
public Person(string name, int age)
{
_name = name;
_age = age;
}
private readonly string _name;
private readonly int _age;
/// <summary>
/// Full name
/// </summary>
public string Name
{
get { return _name; }
}
/// <summary>
/// Age in years
/// </summary>
public int Age
{
get { return _age; }
}
}
}
Now lets extract the namespace, public modifiers, return statements and curly braces:
class Person
Person(string name, int age)
_name = name;
_age = age;
private readonly string _name;
private readonly int _age;
/// <summary>
/// Full name
/// </summary>
string Name
get _name;
/// <summary>
/// Age in years
/// </summary>
int Age
get _age;
Not too bad 30+ lines reduced to 20! But we could do more, what if triple slash comments were assumed to be summary text by default:
class Person
Person(string name, int age)
_name = name;
_age = age;
private readonly string _name;
private readonly int _age;
/// Full name
string Name
get _name;
/// Age in years
int Age
get _age;
16 lines and dare I say it, no less readable!
Perhaps we could merge the class declaration and constructor to define a closure over the class members?
class Person(string name, int age)
/// Full name
string Name
get name;
/// Age in years
int Age
get age;
9 lines and some might say the intent is actually clearer now!
Which incidentally isn’t a million miles away from what we can do with an F# class today:
type Person(name:string,age:int) =
/// Full name
member person.Name = name
/// Age in years
member person.Age = age
Or we could go one step further and take it down to just 1 line with an F# record:
type Person = { Name:string; Age:int }
It’s probably worth mentioning that both the F# class and record types can be consumed as classes from C# in exactly the same way as the original C# example.
So, if like me you’re a little bored of reading and writing verbose C# class declarations then F# might just be your thing!