Sunday, December 11, 2011

F# ≥ C# (Object Expression)

It has been a long week working on various F# libraries. This blog shows how to use Object Expression to make your code more concise.

I was working on a UI project which involves WPF/Metro command binding. The ICommand interface requires two functions: CanExecute and Execute. Because I already have some functions implemented in the F# project, I'd image implement ICommand in F# project is much easier.

In the WPF converter code snippets, I defined a new type to represent the converter. The code is like:

type StringToVisiblityConverter() =
    inherit ConverterBase(stringToInt>>intToBool>>boolToVisibility |> convert, nullFunction)

This technique is very familiar to C# developer. But I do not like the way the code, especially the inherit ConverterBase. What I really want to say is: create a command with two functions. I ended up with the code like the following:

let createCommand action canExecute=
            let event1 = Event<_, _>()
                new ICommand with
                    member this.CanExecute(obj) = canExecute(obj)
                    member this.Execute(obj) = action(obj)
                    member this.add_CanExecuteChanged(handler) = event1.Publish.AddHandler(handler)
                    member this.remove_CanExecuteChanged(handler) = event1.Publish.AddHandler(handler)

     let myCommand = createCommand
                        (fun _ -> ())
                        (fun _ -> true)
createCommand is a template function which takes two functions as input parameter. This function returns a ICommand object. The myCommand takes two dummy functions and generate a concrete object. I can reference this myCommand object from C# without any problem and the code is more readable than C# version.

As a professional developer, I am interested any technique can make my code more readable. How about you?  :-)

No comments: