Skip to content
Nils Lück edited this page Mar 14, 2018 · 4 revisions

Tips and suggested practices

This page will contain tips and best practices for using Optional.

Naming conventions

Methods

When it comes to methods, I use either of the following two conventions:

  1. Don't name methods in a special way.
  2. Prefix methods with Try.

I probably prefer the first one in most cases, but the second one aligns nicely with the conventions used in F#, and very explicitly tells a user that it might not be possible to return a value.

The most important thing is to keep your own APIs consistently named!

Examples:

// Regular method names
public Option<string> FindTitle(Book book);
public Option<Employee> GetEmployee(int employeeId);
public Option<Document> ParseDocument(string document);

// Prefixing with try to be more explicit
public Option<string> TryFindTitle(Book book);
public Option<Employee> TryGetEmployee(int employeeId);
public Option<Document> TryParseDocument(string document);

Properties and variables

Whenever Optional is used for properties in an object, I would suggest to use regular naming conventions.

When retrieving optional values from a method, we will very often need to store the optional value in a variable, and later also store the actual contained value. This means that we need two separate names.

In such cases, I recommend suffixing the variable with orNone, as it is explicit and reads nicely.

Examples:

// Properties:
public Option<Person> Wife { get; set; }

// Local variables:
var documentOrNone = ParseDocument("...");
var document = documentOrNone.ValueOr(Document.Empty);

Working with optional

Retrieving values

Composition of optional values

Designing with Optional

More explicit data modelling

Composing safe APIs