avoiding null reference exceptions

后端 未结 15 1004
天命终不由人
天命终不由人 2020-11-28 08:50

Apparently the vast majority of errors in code are null reference exceptions. Are there any general techniques to avoid encountering null reference errors?

Unless I

15条回答
  •  借酒劲吻你
    2020-11-28 09:20

    Using Null Object Patterns is key here.

    Make sure that you require collections to be empty in the case when they're not populated, rather than null. Using a null collection when an empty collection would do is confusing and often unnecessary.

    Finally, I make my objects assert for non-null values upon construction wherever possible. That way I'm in no doubt later on as to whether values are null, and only have to perform null checks where essential. For most of my fields and parameters I can assume that values are not null based on previous assertions.

提交回复
热议问题