Monday, March 18, 2013

Sasa.Option - Handling Optional Values

This is the fourth post in my ongoing series covering the abstractions in Sasa. Previous posts:

Sasa.Option is an abstraction to deal with nullable/optional values. It is available in the core Sasa.dll. Reference types are already nullable, and structs have System.Nullable, so why write yet another abstraction to deal with optional values?

The answer is pretty simple: there is no other way to write a function whose generic arguments are clearly and plainly optional. This is partially complicated because C# doesn't consider type constraints when selecting method overrides, otherwise you could do something like this:

int Foo<T>(T nullable)
  where T : class
{
    ...
}
int Foo<T>(T notNullable)
  where T : struct
{
    ...
}

The nullable overload is clear from the type information, but this type information is never used and C# complains about ambiguous methods. Technically, you could simply write Foo like so:

int Foo<T>(T possiblyNull)
{
    if (possiblyNull == null)
        ...
    else
        ...
}

This will work even if you pass in Nullable<int> because a Nullable<int> can be compared to null, and so will take the proper branch. However, it's not at all clear from the type signature of Foo that possiblyNull is an optional Value. So Sasa.Option was created to easily specify this sort of contract, and have the contract enforced by the type system:

int Foo<T>(Option<T> possiblyNull)
{
    if (possiblyNull == null)
        ...
    else
        ...
}

Option<T> has safe implicit conversions from T, and comparisons to null are fully defined.

Sasa.Option<T>.Value

Sasa.Option encapsulates a Value that may or may not be there. The Value property of the Option<T> struct returns the encapsulated Value if it exists, or throws InvalidOperationException if no Value exists:

Option<int> someInt = 3;
Console.WriteLine(someInt.Value);
Option<int> noInt = null;
Console.WriteLine(noInt.Value); //InvalidOperationException
// output is:
// 3
// throws InvalidOperationException

This property is also required by IValue<T>, which Option<T> implements.

Sasa.Option<T>.HasValue

To check whether an Option<T> has a Value, just check the HasValue property as you would on a Nullable<T>:

Option<int> someInt = 3;
Option<int> noInt = null;
Console.WriteLine(someInt.HasValue);
Console.WriteLine(noInt.HasValue);
// output is:
// true
// false

This property is also required by the IOptional<T>, which Option<T> implements.

Sasa.Option<T>.TryGetValue

TryGetValue permits accessing the encapsulated Value without throwing an exception if the Value is null:

Option<int> someInt = 3;
int x;
if (someInt.TryGetValue(out x))
  Console.WriteLine(x);
else
  Console.WriteLine("null");

Option<int> noInt = null;
if (noInt.TryGetValue(out x))
  Console.WriteLine(x);
else
  Console.WriteLine("null");
// output is:
// 3
// null

This method is required by the IVolatile<T> interface, which Option<T> implements.

Sasa.Option<T>.| operator

The C# null coalescing operation, ??, is hard-coded to only apply to reference types or System.Nullable<T>. However, the short-circuiting logical-or operator can be overridden, and Option<T> does so to provide option-coalescing:

Option<int> someInt = 3;
Option<int> noInt = null;
Console.WriteLine(someInt || 99);
Console.WriteLine(noInt || 99);
// output is:
// 3
// 99

Sasa.Option.ToOption

The Sasa.Option.ToOption extension methods allow simple conversions to option types, given any Value T or any nullable struct Value T?:

Option<int> someInt = 3.ToOption();
Option<int> noInt = new int?().ToOption();
Console.WriteLine(someInt);
Console.WriteLine(noInt);
// output is:
// 3
// null

Sasa.Option.ToNullable

Given any Option<T>, where T is a Value type, we can easily convert this to a Nullable<T> type using the ToNullable extension method:

int? someInt = new Option<T>.ToNullable();
Console.WriteLine(someInt ?? 99);
// output is:
// 3

Sasa.Option.Try

The Sasa.Option.Try static methods enable clients to execute some piece of code that returns a Value into an Option<T>. If the delegate throws an exception, then Option<T>.None is returned:

Option<int> someInt = Option.Try(() => 3);
Option<int> noInt = Option.Try<int>(() => throw new Exception());
Console.WriteLine(someInt);
Console.WriteLine(noInt);
// output is:
// 3
// null

Sasa.Option.Do

Sasa.Option.Do is an extension method that performs an action specified by a delegate only if the Option<T> has a Value:

Action<int> print = Console.WriteLine;
Option<int> someInt = 3;
Option<int> noInt = null;
someInt.Do(print);
noInt.Do(print);
// output is:
// 3

Sasa.Option.Select

Sasa.Option.Select are extension methods implementing the LINQ select query pattern on Option<T> and Nullable<T>:

Option<int> someInt = 3;
Option<int> noInt = null;
Console.WriteLine(someInt.Select(x => x > 0));
Console.WriteLine(noInt.Select(x => x > 0));
// output is:
// true
// null

Sasa.Option.Where

Sasa.Option.Where extension methods implement the LINQ where clause for query patterns on Option<T> and Nullable<T>:

Option<int> someInt = 3;
Option<int> noInt = null;
Console.WriteLine(someInt.Where(x => x > 0));
Console.WriteLine(someInt.Where(x => x < 0));
Console.WriteLine(noInt.Where(x => x == 0));
// output is:
// true
// null
// null

Sasa.Option.SelectMany

The last essential LINQ operator, Sasa.Option.SelectMany implements all permutations of SelectMany with Nullable<T> and Option<T>, which enables you to use option values in queries:

var val = from y in new int?(2)
          from j in 7.ToOption()
          from x in (y + 2 + j).ToOption()
          select x;
Console.WriteLine(val);

var noval = from y in new int?(2)
            from j in new int?()
            from x in (y + 2 + j).ToOption()
            select x;
Console.WriteLine(noval);
// output:
// 11
// null

No comments: