nodatime / nodatime

A better date and time API for .NET

Home Page:https://nodatime.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Nullable arguments in Parse methods

karol-gro opened this issue · comments

At the moment all Parse methods of different Patterns have an attribute [SpecialNullHandling] to indicate that null is supported, but will result in failed result. However, the argument in not nullable, so this code snippet will trigger compiler warning:

var time = LocalTimePattern.CreateWithInvariantCulture("H:mm").Parse(input)
if (!time.Success) return;

However, it's perfectly fine and has no issues. Personally, I wouldn't expect anyone with nullable string to check it for null before passing to Parse method given they later properly handle the result (which they should do anyway).

If we look at .NET classes, we can see that non-nullable parameters are used only in cases where null triggers exception or undefined result. If method has some defined behavior for null, the parameter is nullable, even if semantically it doesn't make sense. E.g.:

public static class Path {
   public static string? GetPathRoot (string? path); // returns null for null, parameter is nullable
   public static string GetFullPath (string path); // throws exception for null, paramter in not-nullable
}

Given that, I think all Parse methods should have string? parameters. It can still contain the attribute [SpecialNullHandling] (although I'm not entirely sure if it brings any value after removal of a test which was using it), but the question mark will inform all users that they are not required to check for null before passing it to the Parse method.

I'll have a think about it.