The following is a general range class. The purpose of this is to preserve the range, and then later, when required, specify (boolean) if the setpoint is in the range.
I read several posts, questions, blogs, etc. that say "Replace conditional with polymorphism"
My question is: is it really worth allocating code into several classes, where each class will literally have one line of code. Hope the code below will show what I mean.
The class depends on two other classes that are not shown here, but if someone needs it, I can enable it later.
namespace Common.Utilities
{
public class GenericRange<T>
where T : struct, IComparable<T>
{
#region Properties
public T Min { get; private set; }
public T Max { get; private set; }
public GenericRangeType RangeType { get; private set; }
#endregion
#region Constructors
public GenericRange(T min, T max, GenericRangeType rangeType = GenericRangeType.Inclusive)
{
Min = min;
Max = max;
RangeType = rangeType;
}
#endregion
#region Methods
#region Private
private bool IsInclusive(T value)
{
return value.IsGreaterThanOrEqualTo(Min) && value.IsLessThanOrEqualTo(Max);
}
private bool IsInclusiveMin(T value)
{
return value.IsGreaterThanOrEqualTo(Min) && value.IsLessThan(Max);
}
private bool IsInclusiveMax(T value)
{
return value.IsGreaterThan(Min) && value.IsLessThanOrEqualTo(Max);
}
private bool IsExclusive(T value)
{
return value.IsGreaterThan(Min) && value.IsLessThan(Max);
}
#endregion
#region Public
public bool Contains(T value)
{
switch (RangeType)
{
case GenericRangeType.Inclusive: return IsInclusive(value);
case GenericRangeType.InclusiveMin: return IsInclusiveMin(value);
case GenericRangeType.InclusiveMax: return IsInclusiveMax(value);
case GenericRangeType.Exclusive: return IsExclusive(value);
default: throw new NotImplementedException();
}
}
public override string ToString()
{
return String.Format("Min: {0}, Max: {1}, Type: {2}", Min, Max, RangeType);
}
#endregion
#endregion
}
}
: Contain ToString. , , Contain .
, , /?
, . , .
1: , , - :
public static class ComparableExtensions
{
public static bool IsEqualTo<T>(this T leftHand, T value) where T : IComparable<T>
{
return leftHand.CompareTo(value) == 0;
}
public static bool IsGreaterThan<T>(this T leftHand, T value) where T : IComparable<T>
{
return leftHand.CompareTo(value) > 0;
}
public static bool IsGreaterThanOrEqualTo<T>(this T leftHand, T value) where T : IComparable<T>
{
return leftHand.CompareTo(value) >= 0;
}
public static bool IsLessThan<T>(this T leftHand, T value) where T : IComparable<T>
{
return leftHand.CompareTo(value) < 0;
}
public static bool IsLessThanOrEqualTo<T>(this T leftHand, T value) where T : IComparable<T>
{
return leftHand.CompareTo(value) <= 0;
}
}
public enum GenericRangeType
{
Inclusive,
Exclusive,
InclusiveMin,
InclusiveMax
}