Skip to content

Instantly share code, notes, and snippets.

Created January 16, 2013 09:42
Show Gist options
  • Save anonymous/4545932 to your computer and use it in GitHub Desktop.
Save anonymous/4545932 to your computer and use it in GitHub Desktop.
Compare two ways to do the same validation. In both cases, the values for `StartTime` and `EndTime` are strings in the view models, hence the reason they need to be parsed at the beginning of the method.
// First version
// 1. Multiple return statements (> cyclomatic complexity)
// 2. 'Happy' path comes first
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var startTime = TimeSpan.Parse(StartTime);
var endTime = TimeSpan.Parse(EndTime);
if (startTime < endTime)
return new ValidationResult[] { };
return new [] { new ValidationResult("Start Time must be before End Time", new [] { "StartTime", "EndTime" }) };
}
// Alternate version
// 1. Less cyclomatic complexity
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var validationResults = new List<ValidationResult>();
var startTime = TimeSpan.Parse(StartTime);
var endTime = TimeSpan.Parse(EndTime);
if (endTime >= startTime)
validationResults.Add(new ValidationResult("Start Time must be before End Time", new [] { "StartTime", "EndTime" }));
return validationResults;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment