C# - What does the Assert() method do? Is it still useful?

后端 未结 9 1696
青春惊慌失措
青春惊慌失措 2020-12-12 10:37

I am debugging with breakpoints and I realize the assert call? I thought it was only for unit tests. What does it do more than breakpoint? Since I can breakpoint, why should

相关标签:
9条回答
  • 2020-12-12 11:06

    Assert allows you to assert a condition (post or pre) applies in your code. It's a way of documenting your intentions and having the debugger inform you with a dialog if your intention is not met.

    Unlike a breakpoint, the Assert goes with your code and can be used to add additional detail about your intention.

    0 讨论(0)
  • 2020-12-12 11:08

    Assertions feature heavily in Design by Contract (DbC) which as I understand was introducted/endorsed by Meyer, Bertand. 1997. Object-Oriented Software Contruction.

    An important feature is that they mustn't produce side-effects, for example you can handle an exception or take a different course of action with an if statement(defensive programming).

    Assertions are used to check the pre/post conditions of the contract, the client/supplier relationship - the client must ensure that the pre-conditions of the supplier are met eg. sends £5 and the supplier must ensure the post-conditions are met eg. delivers 12 roses. (Just simple explanation of client/supplier - can accept less and deliver more, but about Assertions). C# also introduces Trace.Assert(), which can be used for release code.

    To answer the question yes they still useful, but can add complexity+readability to code and time+difficultly to maintain. Should we still use them? Yes, Will we all use them? Probably not, or not to the extent of how Meyer describes.

    (Even the OU Java course that I learnt this technique on only showed simple examples and the rest of there code didn't enforce the DbC assertion rules on most of code, but was assumed to be used to assure program correctness!)

    0 讨论(0)
  • 2020-12-12 11:11

    The way I think of it is Debug.Assert is a way to establish a contract about how a method is supposed to be called, focusing on specifics about the values of a paramter (instead of just the type). For example, if you are not supposed to send a null in the second parameter you add the Assert around that parameter to tell the consumer not to do that.

    It prevents someone from using your code in a boneheaded way. But it also allows that boneheaded way to go through to production and not give the nasty message to a customer (assuming you build a Release build).

    0 讨论(0)
提交回复
热议问题