如何修改代码以使其遵守德米特定律
public class BigPerformance
{
public decimal Value { get; set; }
}
public class Performance
{
public BigPerformance BigPerf { get; set; }
}
public class Category
{
public Performance Perf { get; set; }
}
如果我打电话:
Category cat = new Category();
cat.Perf.BigPerf.Value = 1.0;
我认为这违反了德米特定律/最少知识原则?< br> 如果是这样,如果我有大量内部类属性,我该如何解决这个问题?
public class BigPerformance
{
public decimal Value { get; set; }
}
public class Performance
{
public BigPerformance BigPerf { get; set; }
}
public class Category
{
public Performance Perf { get; set; }
}
If I call:
Category cat = new Category();
cat.Perf.BigPerf.Value = 1.0;
I assume this this breaks the Law of Demeter / Principle of Least Knowledge?
If so, how do I remedy this if I have a large number of inner class properties?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我最喜欢马丁·福勒的名言之一:
http://haacked.com/archive /2009/07/14/law-of-demeter-dot-counting.aspx
One of my favourite quotes from Martin Fowler:
http://haacked.com/archive/2009/07/14/law-of-demeter-dot-counting.aspx
如果您正在谈论德米特法则,“不要给邻居打电话”,您可以将其委托给其他可以完成您想要的操作的方法。
从你的例子来看,我猜你想重置性能值或其他东西。您可以修改示例代码,使它们本质上链接起来:
代码将类似于:
这样,
Category
类不需要知道如何在默认值的情况下重置值是不同的东西或者它的类型将来会改变。就我个人而言,如果更改的风险较低,我会选择 juharr 的回答 相反。
If you're talking about Law of Demeter as in, "don't call the neighbors of neighbors" you can delegate it to other methods that do what you want.
From your example I'm guessing you want to reset the performance value or something. You can modify the example code so they are chained inherently instead:
The code would be something akin to this:
That way the
Category
class doesn't need to know how to reset the value in case the default value is something different or it's type is changed in the future.Personally if the risk for change is low I'd go for juharr's answer instead.
因此
,如果维基百科的定义是正确的,那么它就违反了规则:
如果您担心这 3 者紧密耦合,请删除公共访问器并在 Category 上添加一个方法来设置值。然后将 Performance 和 BigPerformance 重构为私有成员。
is
So it is breaking the rules if the wikipedia definition is correct:
If you are worried about the 3 being tightly coupled, then remove the public accessors and add a method on Category to set the value. Then refactor Performance and BigPerformance to be private members.
如果您始终牢记类的可测试性并使用 IoC,您会发现不必担心 LoD。
这么看
你的代码将在行中
它看起来(并且在短期内可能是)需要更多的工作,但好处将在从长远来看,能够单独测试您的课程。
请查看 Misco Hevery 博客,了解在这个和其他主题上大开眼界。
If you always keep testabillity of your classes in mind and use IoC, you will notice you don't have to worry about LoD as much.
Look at it this way
Your code would be in the line of
It looks (and in the shortrun probably is) like a lot more work but the benefits will pay off in the long run by being able to test your classes in isolation.
Take a look at Misco Hevery's blog for an eye opener on this and other subjects.
这并没有违反德米特法则,因为你正在使用类的公共契约。
This is not breaking the Law of Demeter, because you are using public contract of classes.