-
Notifications
You must be signed in to change notification settings - Fork 73
Tips
This page will contain tips and best practices for using Optional.
When it comes to methods, I use either of the following two conventions:
- Don't name methods in a special way.
- 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);
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);