Throwing an exception vs Contract.Requires?

后端 未结 2 930
我在风中等你
我在风中等你 2020-12-14 09:28

I\'m wondering whether should I throw exceptions or call Contract.Requires

For example:

public static void Function(String str)
{
          


        
2条回答
  •  悲哀的现实
    2020-12-14 09:53

    I'm not sure that there are any earth-shattering differences between the two approaches, but here are two reasons why I prefer contracts...

    1) The code is much neater, as you are writing a statement at the top of the method that shows the assumptions upon which the method is based. You don't clog up the code with the implementation of what happens if the assumption is violated.

    2) You get the benefit of Visual Studio picking up on the code contracts when you are writing code, and giving you hints as to what the method you are about to call expects. This helps you ensure that you are sending the method valid parameters, without having to jump to the method definition to check the code there.

    Once the code is compiled and running, I don't think there are any significant differences.

    Hope this helps.

提交回复
热议问题