Created
January 16, 2013 09:42
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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