코드의 다음과 같은 두 가지 고려 :C 번호 : 코드 계약 대 일반 매개 변수 유효성 검사
public static Time Parse(string value)
{
string regXExpres =
"^([0-9]|[0-1][0-9]|2[0-3]):([0-9]|[0-5][0-9])$|^24:(0|00)$";
Contract.Requires(value != null);
Contract.Requires(new Regex(regXExpres).IsMatch(value));
string[] tokens = value.Split(':');
int hour = Convert.ToInt32(tokens[0], CultureInfo.InvariantCulture);
int minute = Convert.ToInt32(tokens[1], CultureInfo.InvariantCulture);
return new Time(hour, minute);
}
및
을public static Time Parse(string value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
string[] tokens = value.Split(':');
if (tokens.Length != 2)
{
throw new FormatException("value must be h:m");
}
int hour = Convert.ToInt32(tokens[0], CultureInfo.InvariantCulture);
if (!(0 <= hour && hour <= 24))
{
throw new FormatException("hour must be between 0 and 24");
}
int minute = Convert.ToInt32(tokens[1], CultureInfo.InvariantCulture);
if (!(0 <= minute && minute <= 59))
{
throw new FormatException("minute must be between 0 and 59");
}
return new Time(hour, minute);
}
코드가 훨씬 명확하고 작기 때문에 개인적으로 첫 번째 버전을 선호
, 계약을 쉽게 끌 수 있습니다. 그러나 단점은 Visual Studio 코드 분석에서 null에 대한 매개 변수 값을 확인해야한다는 것이고 생성자의 계약은 분과 시간이 주어진 경계 내에 있음을 보장하지 않는다는 것을 인식하지 못한다는 것입니다.
그래서 나는 많은 잘못된 경고를 받고 결국 RegEx 유효성 검사가 아닌 FormatExceptions를 던지면서 계약으로 문자열 값의 유효성을 검사 할 수있는 방법이 없습니다.
코드 계약을 사용하여 이와 동등한 상황을 어떻게 해결할 수 있을지 제안 하시겠습니까? 위해
을 사용할 수 있습니다 경고를 없애? 두 가지 예가 그렇지 않은 경우보다 더 유사하게 만듭니다. –