我发现在我的代码中经常发生以下错误,并且想知道是否有人知道一些避免它的好策略.
想象一下这样的一个类:
public class Quote
{
public decimal InterestRate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在某些时候,我创建了一个利用利率的字符串,如下所示:
public string PrintQuote(Quote quote)
{
return "The interest rate is " + quote.InterestRate;
}
Run Code Online (Sandbox Code Playgroud)
现在想象一下,我将InterestRate属性从小数重构为它自己的类:
public class Quote
{
public InterestRate InterestRate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
...但是说我忘了重写InterestRate类中的ToString方法.除非我仔细查找InterestRate属性的每个用法,否则我可能永远不会注意到它在某些时候被转换为字符串.编译器当然不会选择它.我唯一的救世主机会是通过整合测试.
下次我调用PrintQuote方法时,我会得到一个这样的字符串:
"利率为Business.Finance.InterestRate".
哎哟.如何避免这种情况?
Mif*_*Fox 10
通过在IntrestRate类中创建ToString的覆盖.