Slick Use Case For Active Patterns

So I love it when a very natural use case arises for a feature that I want to practice.  I’ve been trying to better my understanding of active patterns lately and today I found a great use for them.

I’m fetching json data from a REST endpoint.  Of course I get back a string.  And the string contains some very specific text when there’s a problem processing the request on the server side.  So I ended up doing something like this:


let errResult = "Error creating user"

let (|ContainsErrString|) (stringToTest:String) = stringToTest.Contains(errResult)

//And further down in the code:

let res = sr.ReadToEnd()

let u1 =
 match res with
 | ContainsErrString true -> None
 | _ -> Some(JsonConvert.DeserializeObject<user>(res))

Simplifies the code dramatically and hides detail that the match doesn’t need to know about.  Terrific use case for an active pattern.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: