在我工作的一个大项目中,我正在考虑建议其他程序员如果没有考虑他们的课程应该如何分类,他们总是密封他们的课程.很少有经验的程序员从不考虑这一点.
我发现奇怪的是,在java和c #classd中是非密封/非最终的pr默认值.我认为密封课程大大提高了代码的可读性.
请注意,这是内部代码,如果发生我们需要子类的罕见情况,我们可以随时更改.
你有什么经历?我对这个想法遇到了很多阻力.是懒惰的人,他们不能打扰"密封"吗?
假设我有以下设置:
public interface IFoo
{
string DoSomething();
string DoAnotherThing();
}
public sealed class Bar : IFoo
{
public string DoAnotherThing() => "DoAnotherThing";
public string DoSomething() => "DoSomething";
}
Run Code Online (Sandbox Code Playgroud)
使用 Moq,我想模拟 的一种方法Bar,但调用另一种方法的实现。我知道我可以通过创建一个委托给的包装类来做到这一点Bar,如下所示:
public class MockableBar : IFoo
{
private readonly IFoo _bar;
public MockableBar(IFoo bar) => _bar = bar;
public virtual string DoAnotherThing() => _bar.DoAnotherThing();
public virtual string DoSomething() => _bar.DoSomething();
}
Run Code Online (Sandbox Code Playgroud)
然后像这样嘲笑它:
var fake = new Moq.Mock<MockableBar>(new Bar()) { CallBase = true };
fake.Setup(_ => _.DoSomething()).Returns("Mock"); …Run Code Online (Sandbox Code Playgroud)