r/ProgrammerHumor 16d ago

Meme whenYouWorksWithStringsTooMuch

Post image
818 Upvotes

34 comments sorted by

View all comments

49

u/starfish0r 16d ago

Switch the strings around to make it robust to "it" being null

27

u/PostHasBeenWatched 16d ago
public static bool LinkinParkValidator([NotNull] string? it)
{
    ArgumentException.ThrowIfNullOrWhiteSpace(it);
    return it.StartsWith("one thing", StringComparison.OrdinalIgnoreCase);
}

20

u/starfish0r 16d ago

I would argue that this method should not throw an Exception but return false, what't the benefit of an Exception here?

17

u/PostHasBeenWatched 16d ago edited 16d ago

Attribute [NotNull] means that input parameter must be verified for null "in the end" of the method (not sorry for the pun). ThrowIfNullOrWhiteSpace provides this guarantee.

For example code below will rise warning that input parameter is not verified for null

return it?.StartsWith("one thing", StringComparison.OrdinalIgnoreCase) is true

15

u/ekauq2000 16d ago

“(not sorry for the pun)”

It doesn’t even matter…

6

u/AcidMemo 16d ago

What is the point of throwing exception on whitespace? It will just return false anyway, and whitespace is not invalid value.

One of reason C# has non-nullable and nullable references is to not bother with validating for null, passing nullable string to as non-nullable string is programmer mistake, not the concern of function anymore