This repository was archived by the owner on Jun 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Defensive coding: Possible of T
Yves Schelpe edited this page Dec 5, 2017
·
2 revisions
Provides a type Possible<T> that abstracts away null.
- One can convert any object to IPossible
var possible = Possible.From(1);
possible = 1.ToPossible();
- That way, when an object contains null, and you wouldn't know it beforehand the Possible class will take that into account for you:
int? nullableInt = null;
var possibleIntFromNullableViaStaticMethod = Possible.From(nullableInt);
var posibleIntFromNullableViaExtensionMethod = nullableInt.ToPossible();
object @object = null;
var possibleObjectViaStaticMethod = Possible.From(@object);
var possibleObjectViaExtensionMethod = @object.ToPossible();
- You can pass in an optional lambda to determine whether an object is null or not, used below is the default expression when you pass no lambda which just checks whether the object is not null, then Possible.From assumes you have a value by "convention":
object @object = null;
var possibleObjectViaStaticMethod = Possible.From(@object, o => o != null);
possibleObjectViaExtensionMethod = @object.ToPossible(o => o != null);
- For string objects you can define a parsing strategy, the default one is
StringValueParserStrategy.NullEmptyOrWhitespaceIsNoValuewhich translates toString.IsNullOrWhiteSpace()
var possibleStringViaStaticMethod = Possible.From(" ");
var possibleStringViaExtensionMethod = " ".ToPossible();
possibleStringViaStaticMethod = Possible.From(" ", StringValueParserStrategy.NullOrEmptyIsNoValue);
possibleStringViaExtensionMethod = " ".ToPossible(StringValueParserStrategy.NullOrEmptyIsNoValue);
- Given a possible object, one can get the original value back, but since you have no idea whether it contains a value or not, you are always obliged to pass in either a fixed default value or a function the produces a default value
var possible = "".ToPossible();
var real = possible.GetValue(""); // pass in a fixed value as the default
real = possible.GetValue(() => String.Empty); // pass in a function the produces a default value