I have some fairly simple code (C#):
/// <summary>
/// Truncates a string to a maximum length.
/// </summary>
/// <param name="value"> The string to truncate. </param>
/// <param name="maxLength"> The maximum length of the string. </param>
/// <returns>
/// The original string if its length is less than or equal to max length, else a truncated
/// string of length maxLength.
/// </returns>
public static string Truncate(string value, int maxLength)
{
if(maxLength <= 0) throw new ArgumentOutOfRangeException("maxLength");
if (string.IsNullOrEmpty(value)) return value;
return value.Length <= maxLength ? value : value.Substring(0, maxLength);
}
It's clear that if maxLength
is less than 0, I can't use it as a string length, and so I am currently using a guard statement to prevent invalid maxLength
values.
My question is: is it good or bad practice to use this guard statement, when value.Substring
will throw the same exception anyway? Is it just wasted code?