这是我正在使用随机类的包装器扩展的代码。
public static class RandomHelper
{
private static int currentSeed;
private static Random rd = new Random();
public static double Next()
{
return rd.NextDouble();
}
public static double Next(double min, double max)
{
return (rd.NextDouble() * (max - min)) + min;
}
public static double NextOnStep(double min, double max, double step)
{
int range = (int)Math.Floor((max - min) / step);
int stepCount = rd.Next(0, range);
return min + (step * stepCount);
}
public static double NextOnDecimalCount(double min, double max, int decimals)
{
double step = Math.Pow(10, decimals);
return Math.Truncate(((rd.NextDouble() * (max - min)) + min) * step) / step;
}
想象一下这种情况,我有一个包含三个数字范围的课程
public class ArithmeticProblemGenerator()
{
Range Number1Range {get;set;}
Range Number2Range {get;set;}
...
Range Number5Range {get;set;}
}
public class Range
{
public Range()
{
}
public Range(double min, double max)
{
this.Min = min;
this.Max = max;
}
public double Min { get; set; }
public double Max { get; set; }
}
当我想要生成问题时,我在RandomHelper中添加另一个方法作为extesion。
#region RandomHelper extensions
public static double Next(Range range)
{
return Next(range.Min, range.Max);
}
public static double NextOnStep(Range range, double step)
{
return NextOnStep(range.Min, range.Max, step);
}
public static double NextOnDecimalCount(Range range, int decimals)
{
return NextOnDecimalCount(range.Min, range.Max, decimals);
}
#endregion
但是后来我添加了ArithmeticProblemGenerator的一个新功能,我想要有不同小数位的数字,或者有时数字会跟着一步。
所以,我认为,创建另外两个类来添加以下功能是不错的。
public class RangeOnStep : Range
{
public RangeOnStep()
{
}
public RangeOnStep(double min, double max, double step)
: base(min, max)
{
this.Step = step;
}
public double Step { get; set; }
}
public class RangeOnDecimalPlace : Range
{
public RangeOnDecimalPlace()
{
}
public RangeOnDecimalPlace(double min, double max, double decimalPlaces)
: base(min, max)
{
this.DecimalPlaces = decimalPlaces;
}
public double DecimalPlaces { get; set; }
}
使用这些新类添加其他方法扩展。你认为我做得很好还是设计混乱?
我想听听建议或意见。提前谢谢。
答案 0 :(得分:1)
方法扩展在这里没用,为什么不使用基类范围并定义覆盖方法,如:
公共静态类RandomHelper { private static int currentSeed; private static Random rd = new Random();
public static double Next()
{
return rd.NextDouble();
}
public static double Next(double min, double max)
{
return (rd.NextDouble() * (max - min)) + min;
}
public static double Next(RangeOnStep r)
{
int range = (int)Math.Floor((r.max - r.min) / r.step);
int stepCount = rd.Next(0, range);
return r.min + (step * stepCount);
}
public static double Next(RangeOnDecimalPlace r))
{
double step = Math.Pow(10, r.decimals);
return Math.Truncate(((rd.NextDouble() * (r.max - r.min)) + r.min) * step) / step;
}
答案 1 :(得分:0)
我在使用静态帮助程序类(无论是否扩展方法)时发现的一个问题是,在涉及依赖于这些静态的单元测试代码时,它们很难被模拟。对于您的情况也是如此,因为您无疑要测试随机数生成器返回特定范围内的值的情况。
我通常尝试用带有接口的实例类替换静态助手,然后使用IoC将“助手”的单个注入到我的依赖类中(即仅在接口上耦合) - 这样助手就可以了被嘲笑,你的班级经过全面测试。