Reputation: 1379
I need to find if all conditions fit a certain criteria.
public class OfferServiceConditionDto
{
public long Id { get; set; }
public Parameter Parameter { get; set; }
public Enums.Condition Condition { get; set; }
public double? Value { get; set; }
[JsonIgnore]
public long? OfferSubServiceId { get; set; }
}
Parameters has 5 cases:
public enum Parameter : int { Length, Width Height, Area, Volume }
Condition has 6 cases:
public enum Condition : int
{
LessThan,
LessThanOrEqualTo,
Equals,
GreaterThan,
GreaterThanOrEqualTo,
DoesNotEqual
}
IN my function I am given an element width height and length and I need to check against OfferServiceConditionDto conditions, paremeters and value.
So far I am only thinking switch cases or ifs but that's a whooping 30 checks.
Any better alternative for this?
Upvotes: 1
Views: 85
Reputation: 273380
Just extract some methods. By doing so, you can easily turn 30 (5 * 6) cases into 11 (5 + 6).
public static bool CheckCondition(double width, double height, double length, OfferServiceConditionDto dto) {
switch (dto.Parameter) {
case Parameter.Length:
return CheckCondition(dto.Condition, length, dto.Value);
case Parameter.Height:
return CheckCondition(dto.Condition, height, dto.Value);
// plus 3 more...
}
return false;
}
private static bool CheckCondition(Enums.Condition condition, double value1, double? value2) {
if (value2 == null) {
return true; // decide what to do if Value is null
}
switch (condition) {
case Enums.Condition.LessThan:
return value1 < value2.Value;
case Enums.Condition.LessThanOrEqualTo:
return value1 <= value2.Value;
// plus 4 more...
}
return false;
}
Upvotes: 4