Working friendly with Null Object references through extended functions

Source: Internet
Author: User
Codeproject
Introduction

I hate the Null Object reference error. it will decrease not only the quality but also the customer satisfaction. entering the C #3.0 times, the extended functions give us a powerful way to change our coding styles, including the approaches to null object references.

Rationalities for null references

However, the Null Object Reference is reasonable. It is impossible to be eliminated from the codes. Dozens of codes will bring up null object references. They fall into at least three categories.

1. Widely used third-party components

Third party components prosper in the software development circles. it's well-known that they boost the productivity, even the quality and scalability. however, not all the third party components are shipped with sufficient document to direct the programmers to code correctly with their interfaces, which will result in Null Object Reference errors.

2. Web Services

In common sense, the response object returned from the Web Service proxy cocould not be null. however, the array in the response object will be null even if the web service returns an empty array instead of null.

3. List <t>. findcommon approaches for null object references

Let's start with a function definition.

Public class timescheme {public long schemeid {Get; set;} public long [] timeid {Get; set;} Public String schemename {Get; set ;}} public void saveobj (timescheme scheme, int count ){//...}

The parameter list of saveobj function contains two parameters. Parameter scheme is a reference type that may be null object reference. Parameter count is a value type that never causes Null Object reference error.

Approach 1: just think they always have instances

Just ignore you are coding with reference types. Rather, handling them as the way as value types. Here is the pre-condition that they can't be null. The Code is as follows:

Public void saveobj (timescheme scheme, string name, int count) {Switch (scheme. schemeid) {Case 1: // do something break; Case 2: // do something break ;}}

If the scheme is null, the Null Object reference error arises. however, it is not bad. the pre-condition is that the scheme can not be null normally, if the null reference error arises, it indicates that something wrong in the running context. the exception will stop the error into the following workflow so that more serous bugs can be avoided. meanwhile, the user and the programmer are alerted as well.

From the practical perspective, the code above is not valid tive to help us find the problem accurately. If the Null Object reference error appears in saveobj, we can only get the message as the following form.

Test method mytest. unittest1.testnullreference threw exception: system. nullreferenceexception: object reference not set to an instance of an object.
Mytest. unittest1.saveobj (timescheme scheme, string name, int32 count) in c: \ mytest \ unittest1.cs: Line 131

In other words, we are alerted that Null Object Reference arises in saveobj function. However, we can't figure out which reference value cause the error.

To be frank, the code above is almost useless to help us find out the problem. If we write more code to guard the scheme value, the error message will be more helpful.

Public void saveobj (timescheme scheme, string name, int count) {If (scheme = NULL) throw new argumentnullexception ("Scheme"); Switch (scheme. schemeid) {Case 1: // do something break; Case 2: // do something break ;}}

The error message will be the following.

Test method mytest. unittest1.testnullreference threw exception: system. argumentnullexception: value cannot be null.
Parameter Name: Scheme.Mytest. unittest1.saveobj (timescheme scheme, string name, int32 count) in c: \ mytest \ unittest1.cs: Line 131

However, if we implement this approach strictly, then codes as if (scheme = NULL) will be added. it will increase the code scale as well as the typing workloads. here is the problem we will address.

Approach 2: think they may be null references

Here is the pre-condition that they can be null. So we must keep it in mind, evaluating the variable before using them. The Code will be written similar to the following form.

Public void saveobj (timescheme scheme, string name, int count) {If (scheme! = NULL) {Switch (scheme. schemeid) {Case 1: // do something break; Case 2: // do something break ;}}}

If we implement this approach strictly, then if-else codes will be introduced into the already-being-complex project. Can we make it simplier?

More practically, both of the pre-conditions may exist in the same context.

The answer to the Null Object references

Since the Null Object references are reasonable, the answer wocould be how we can work friendly with the Null Object references substantially.

For pre-condition that the values can't be null object references, the code will be written in this form.

 
Public void saveobj (timescheme scheme, string name, int count) {Switch (scheme. unsafeitem ("Scheme "). schemeid) {Case 1: // do something break; Case 2: // do something break ;}}

If the variable scheme is null, we can get the more helpful message as the following. Test Method mytest. unittest1.testnullreference threw exception:

System. argumentnullexception: value cannot be null.
Parameter Name: Scheme.
Nova. safeitems. extendenumerable. unsafeitem [T] (T item, string itemname) in c: \ mytest \ safeitems. CS: Line 203
Mytest. unittest1.saveobj (timescheme scheme, string name, int32 count) in c: \ mytest \ unittest1.cs: Line 138
Mytest. unittest1.testnullreference () in c: \ mytest \ unittest1.cs: Line 153

Oh, line 138 is line where the error occurs. We almost don't change the code doesn't the unsafeitem ("Scheme"), which is a extended method.

For pre-condition that the variable may be null object references, the code will be written in this form.

Public void saveobj (timescheme scheme, string name, int count) {scheme. safeitem (n) => {Switch (N. schemeid) {Case 1: // do something break; Case 2: // do something break ;}});}

The switch block will be implemented only if scheme is not null.

Safeitem <t> (this t, Action <t>) makes sure that action <t> is invoked only if variable t refers to a valid reference. unsafeitem <t> (this t, string) throws argumentnullexception if the variable t refers to null reference. in addition, more safe series of extended functions are shipped in safeitems. CS. I believe they will change the way of writing code.

Here I 'd like to end up the writing with a comparison between the traditional codes and the extended safe codes in the real world.

[The traditional codes]

Private Static bool checktimes (searchtimeparameter parameter, datetime startdate) {If (parameter. isxbooking & parameter. item. centraltimes! = NULL & parameter. item. times. length> 0) {foreach (datetime time in parameter. item. times) {If (time. timeofday = startdate. timeofday) {return true ;}} return false ;}else {return true ;}}

[The extended safe codes]

Private Static bool checktimes (searchtimeparameter parameter, datetime startdate) {return! Parameter. unsafeitem ("parameter "). isxbooking | parameter. item. unsafeitem ("parameter. item "). times. safecount = 0 | parameter. item. times. safeexists (time => time. timeofday = startdate. timeofday );}

Don't you think the extended safe codes are simpler?

Tips in unsafeitem

Unsafeitem is just an idea in using the extended functions in C #3.0.

Public static t unsafeitem <t> (this t item, string itemname) where T: Class {If (item = NULL) throw new argumentnullexception (itemname); else return item ;}

 

 

I will appreciate any of your ideas.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.