假设我有一个像这样的长期建立的存储库:
interface IDonutRepository
{
public IEnumerable<Donut> GetDonuts();
}
它已经存在了很长时间,GetDonuts
方法按照它说的做。然后有一天我需要添加一个新屏幕来显示数据库中的所有 donut ,事实证明该方法有一个隐藏的功能 - 它过滤掉所有 stale = true
的 donut 。但是在我的新屏幕上,我想显示所有这些,甚至是陈旧的!这里最好的方法是什么?
假设这个方法在所有地方都被使用,并且默认行为需要保持不变,最好是添加一个名为 GetAllDonuts
的新方法,它不进行过滤,或者我应该只在 GetDonuts
方法上添加一个 onlyFresh
参数吗?
我猜这只是判断,但我想知道是否有更明智的答案?
最佳答案
我会重载该方法,创建一个采用 showStale
参数的新重载,然后修改旧方法以使用新的重载传递 false
作为参数值。
界面看起来像这样:
interface IDonutRepository
{
public IEnumerable<Donut> GetDonuts();
public IEnumerable<Donut> GetDonuts(bool showStale);
}
或者,如果您使用的是 .NET 4.0,则可以使用可选参数:
interface IDonutRepository
{
public IEnumerable<Donut> GetDonuts(bool showStale = false);
}
关于c# - 添加一个参数,还是创建一个新方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5409423/