Why Some/None is better than null

People interested in the advantages for F# might do well to take a look at F# option type. This allows an F# programmer to specify the presents or absence of some data much the same way a C# programmer might use a null reference.

 

Let us take a quick look at how you might use the option type. It is implemented as a discriminating union so can be investigated with F#’s pattern matching constructs.

 

let nodeText = match (get_single_node node “/fruit/apples”) with

            | None -> “”

            | Some node -> get_node_text node

 

If we imagine get_single_node and get_node_text are functions from a ml style Xml api, we can see that above snippet will get the inner text from a single node at the location “/fruit/apples” and if the node does not exist it will return the empty string.

 

At first this may look overly verbose if you compare it with a similar C# snippet.

 

string nodeText = node.SelectSingleNode(“/fruit/apples”).Value

 

But here the C# programmer has made a mistake which is common amongst the young players. If the node does not exist then this snippet will throw a NullReferenceException, this can be a nightmare to debug if a method contains lots of statements like the above, as it can be difficult to spot which item is returning null.

 

While there is nothing stop the C# programmer checking the item returned reference to set a default value, or throw a more meaningful exception. In the F# way of doing this the programmer is reminded to do this as the compiler will issue an incomplete pattern matching warning if they forget to set a default value.

Bookmark
dotnetkicks+, digg+, reddit+, del.icio.us+, dzone+, facebook+

Print | posted @ Monday, March 28, 2005 7:19 AM

Comments on this entry:

No comments posted yet.

Your comment:

(Note: all comments are moderated so it may take sometime to appear)

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 2 and 2 and type the answer here:
 

Links

 Subscribe in a reader
Twitter Follow me on Twitter
FaceBook View my Facebook
LinkedIn View my LinkedIn Profile Viadeo Viadeo Profile (Français)

Badges



Disclaimer

The views expressed on this weblog are mine and do not necessarily reflect the views of my employer.

All postings are provided "AS IS" with no warranties, and confer no rights.


follow robertpi at http://twitter.com