There is an inconsistency - negative values of maxLength
would be forgiven for value
being null
, but cause an exception for every other input (since Substring
would throw an ArgumentOutOfRangeException
).
There's two possible approaches that remove this inconsistency - fail fast
public static string WithMaxLength(this string value, int maxLength)
{
if (maxLength < 0)
{
throw new ArgumentOutOfRangeException("maxLength must be equal to or greater than 0");
}
// ...
Or ignore negative values for both cases:
public static string WithMaxLength(this string value, int maxLength)
{
if (value == null)
{
return null;
}
if (maxLength < 0)
{
return "";
}
return value.Substring(0, Math.Min(value.Length, maxLength));
}
Personally I'd be inclined to choose the former - maxLength
being smaller than 0 could be a symptom of a problem (implementation error) that we wouldn't want to sweep under the carpet. It's also consistent with the way Substring
itself behaves.
WithMaxLength(null, 1)
doesn't throw an exeption whereasWithMaxLength("", 1)
would? \$\endgroup\$ – Konrad Morawski Aug 15 '15 at 19:16