什么是保护方法/类?
我刚刚注意到这个问题中提到的保护方法/类,但我并没有真正理解从答案中得出的概念。可惜的是,乔恩·斯基特 (Jon Skeet) 的 MS 网站链接从未加载。一些快速的谷歌搜索似乎只产生了产品,而不是软件工程概念。
任何解释和/或样品将不胜感激。 (特别是从 .Net 方面来看。)
i just noticed the guard method/class mentioned in this question and i don't really get the concept from the answers. And alas, Jon Skeet's link to an MS site never loaded. A few quick Google searches seemed to yield only products, not software engineering concepts.
Any explanation and/or samples would be appreciated. (Especially from the .Net side of things.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
保护子句是面向方面编程的一部分,您可以在其中定义方法允许的输入。
根据我对 .Net 实现的了解(我还没有真正研究过),您可以使用属性来执行此操作,例如,
我实际上知道 Erlang 中的保护表达式是什么,其中方法分派依赖于保护方法。我将在下面给出一些伪代码来说明这一点:
可能不太明显,您可以在防护中提供一个表达式,该表达式在调度期间进行评估。很整洁,嘿?
Guard clauses are a part of aspect oriented programming, where you can define what is an allowable input to a method.
From what I know of the .Net implementation (which I haven't really looked into), you do this with attributes, e.g.
I actually know what guard expressions are from Erlang, where the method dispatch is dependant on the guard methods. I'll give a bit of psuedocode below to illustrate the point:
As might not be obvious, you could provide an expression in the guard which is evaluated during dispatch. Pretty neat, hey?
如果您不指定异常,.NET 将引发
RaiseContractFailedEvent
,但您可以指定ArgumentOutOfRangeException
或ArgumentNullException
。如果您查看 Jon Skeet 的链接,在文档 pdf 中您会看到许多示例,其中之一是:
这是合同设计的一部分,您可以在其中指定前提条件和后置条件。优点是在使用输入参数之前不必进行大量验证,并且它可以帮助调用函数知道结果将根据约定,因此,如果不允许返回字符串如果是 null,则由于前置条件检查,您在调用该函数时不必测试 null。
If you don't specify an exception then .NET will throw a
RaiseContractFailedEvent
, but you can specifyArgumentOutOfRangeException
orArgumentNullException
.If you look at Jon Skeet's link, at the documentation pdf you will see many examples, one is:
This is part of Contract Design, where you specify preconditions and postconditions. The advantage is that you don't have to do a lot of validation before using the input parameters, and it helps the calling function to know that the result will be according to the contract, so, if the string return isn't allowed to be a null then you don't have to test for null when calling the function, due to the precondition checking.
这是典型保护子句用例的一个很好的概述:
重构保护子句,或“如何礼貌地询问”
This is a pretty good rundown of what a typical guard clause use-case looks like:
Refactoring guard clauses, or “How to ask politely”