Archive for Tips

Value Objects in F#

Value Objects are objects that can be shared across different parts of a program. This can have great benefits in performance. Because  the objects are shared it is very important for value objects to be immutable. If value objects are not immutable then any part of the program can change the values and all the other parts can do calculation with erroneous data.

One of my goals was to make immutable objects in F# to take advantage of parallelization and automatic compiler optimizations:


type City(Name:string, X: float, Y:float) =

member t.Name = Name

member t.X = X

member t.Y = Y

type NeighborCities(city1:string, city2:string) =

member x.fromCity = city1

member x.toCity = city2

Objects created in this manner in F# are immutable. Even when they are accessed in other projects outside their definition, their members are read-only. This was specially helpful on the distributed traveling salesman problem I built last year.

Testing F#

F# is very cool. By combining the regular iterative features of the other .NET languages with an Ocaml syntax variant, F# is extremely flexible and powerful.

Here is a simple loop:

 for i in 0..loopSize do

Here is another example for reading in contents from a file, making an object city and returning a list of cities:


let ReadFile (s:string) = match s with
    | null -> raise (ApplicationException "Please provide a non-empty string for the filename!!")
    | s ->
    let cityList = new ResizeArray<CityDef.City>() in
    let rec ReadFile (r:StreamReader) =
        if not r.EndOfStream then
            cityList.Add(ParseCityString(r.ReadLine()))
            ReadFile r
        r.Close()
    let r = new StreamReader(s) in
    ReadFile r
    cityList

F# has powerful features because it has a lot of high order functions on top of the usual map, filter and reduce. The extra high order functions (such as iter, fold, scan, skip, skipWhile, sum, take, takeWhile, truncate, unfold, windowed, zip, zip3, etc.) make it easy to compound complex tasks.

The next example is a little snippet that returns a dictionary distances between cities for a small distributed traveling salesman problem I did last year to test F# on a software engineering class.


let squared x = x*x

let CompareNeighbors = {
    new System.Collections.Generic.IEqualityComparer<CityDef.NeighborCities> with
    member x.Equals(a,b) =  (String.Compare(a.fromCity, b.fromCity) = 0 ) && ( String.Compare(a.toCity, b.toCity) = 0 )
    member x.GetHashCode(a) = a.toCity.GetHashCode() }

let Distance (distanceDic : Dictionary<CityDef.NeighborCities, double>, i: CityDef.City, j: CityDef.City ) =
    let x2 = squared (i.X - j.X)
    let y2 = squared ( i.Y - j.Y)
    let total = sqrt( x2  +  y2)
    let n = new CityDef.NeighborCities(city1 = i.Name, city2 = j.Name)
    distanceDic.Add(n, total)

type DistanceDictionary() =
    interface Infrastructure.IDistanceCalculator with
        member this.DistanceDictionary (genericListOfCities:ResizeArray<CityDef.City>)  =
            let dic = new Dictionary<CityDef.NeighborCities, double>(CompareNeighbors)
            Seq.iter(fun z -> Seq.iter(fun x->Distance(dic, z, x)) genericListOfCities) genericListOfCities
            dic

Also it is nice being able to use interfaces with F# in the simple format of “interface Infrastructure.IDistanceCalculator with”.

As a little tip, for applying something to a list that does not require a new collection, it is important to avoid using the higher order function map. Map should only be used if a new list with a different set of values is expected because it creates a new list. In this case, map was not necessary and iter was the choice.

Dynamic Azure Web Services URLs

I am currently building a lot of web services for Azure. Since URLs change a lot in development and deployment environments I needed to be able to have those services URLs updated dynamically. The easiest way I found is using handlers and:


HttpContext.Current.Request.Headers["Host"];

This way none of the URLs get hard-coded and deployment is extremely easy. This also brings a lot of neat options for Intercloud communication, but that is for another post.

Synergy and Visual Studio

Currently I am running a windows 7 machine, ubuntu test server and a perosnal macbook pro at my desk . All of them are being controlled by one pair of mice and keyboard which is why  I am a big fan of synergy. The only issue that I was experiencing is that most times visual studio was trapping my mouse and not letting me move it to the next screen.  The trick is to start synergy under the administration account, it solved all problems.

Unitiy IOC

Basically, with Unity, I ended up writing something like this (simplified version) :

IUnityContainer container = new UnityContainer();

container.RegisterType<IRiskRepository, RiskRepository>();

string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

container.Configure<InjectedMembers>().ConfigureInjectionFor<RiskRepository>(new InjectionConstructor(conn));

UnityControllerFactory factory = new UnityControllerFactory(container);

ControllerBuilder.Current.SetControllerFactory(factory);

Unity turned out to work very well. I was able to save a lot of lines of code and it is greatly improving the testability of the dynamic modules I am using on the mock project architecture. Also, it was easy to set up. Its a good alternative to the other more popular IOC.

Namespaces be gone

If you do not need specific namespaces, remove them. Most of the time it is not a big deal in small projects but specially on ASP.NET websites projects it can make a difference. The main difference is that  the compilation time can be significantly reduced and it will speed up your IDE.

If the website contains a lot of namespaces and if the project has C# 3.0 + which enables the use of extension methods it can make a significant difference. By having a lot of namespaces and using extension methods it can make the autocomplete list huge!

One last thing to note that you wont see any particular speed up on the actual execution time of the project if you remove them, they will not affect performance at all once the application is compiled. Its just one of those practices that makes development a bit faster and nicer specially in old computers like the ones I use at work.