Checking arguments for null in Nemerle: revisited

It's turned out that Nemerle has full fledged design-by-contract feature! Let's see how the code from the previous post can be rewritten:

class Person
{
public Name: string;
public this(name: string)
requires name != null
{
Name = name;
}
}
// causes nice "Nemerle.Core.AssertionException: assertion ``name != null''
// failed in file Main.n, line 105: The ``Requires'' contract of method `.ctor' has been violated."
def person = Person(null);
view raw gistfile1.n hosted with ❤ by GitHub
It's really both elegant and powerful compared to hand-written "if (arg == null) throw new ArgumentNullException(...)" or using the Microsoft contracts library.

Contracts may be bond right to arguments themselves:

class Person
{
public Name: string;
public Age: int;
public this(requires (name != null && name.Length > 0) name: string,
requires (age > 0) age: int)
{
Name = name;
Age = age;
}
}
def person = Person("", 30);
view raw gistfile1.txt hosted with ❤ by GitHub

Which causes: "Nemerle.Core.AssertionException: assertion ``name != null && name.Length > 0'' failed in file Main.n, line 107: The ``Requires'' contract of parameter `name' ha s been violated." Amazing! :)

However, if checking for null value is what's only needed, there's one more option: the NotNull macro attribute:

class Person
{
public Name: string;
public this([NotNull] name: string)
{
Name = name;
}
}
view raw gistfile1.n hosted with ❤ by GitHub

Comments

Popular posts from this blog

Haskell: performance

Regular expressions: Rust vs F# vs Scala

Hash maps: Rust, F#, D, Go, Scala