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:
It's really both elegant and powerful compared to hand-written "if (arg == null) throw new ArgumentNullException(...)" or using the Microsoft contracts library.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Contracts may be bond right to arguments themselves:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person | |
{ | |
public Name: string; | |
public this([NotNull] name: string) | |
{ | |
Name = name; | |
} | |
} |
Comments