Wednesday 23 August 2017

Oresund Bridge

Maybe you know that there is a bridge that joins Denmark to Sweden, bridging the 16 kms gap between Copenhagen and Malmo. Maybe you've seen some pic like this:

A beautiful piece of engineering, for sure. But if you see a picture like this you'll probably be shocked!

What the fuck? A bridge to nowhere? This is a joke or what?

Well, I didn't go through that astonishment cause I had watched this documentary before. There they explain that the Oresund link is indeed a tunnel and a bridge.
The Copenhagen side of the link is just next to the Airport, and having started a high rise bridge there would have caused trouble with air traffic. A 16 kms tunnel would have been too expensive, so the solution was to mix both. A 4 kms tunnel starts in Copenhagen and goes up into an artificial island where the road/tracks run for 4 kms until reaching the 8 kms bridge that ends in the Swedish coast.

Crossing it by train as I recently did is pretty fast. When travelling from Denmark to Sweeden, when you emerge into the surface you'll see the so famous Turning Torso on your left, dominating the whole region of Scania.

By the way, I should write a post about this trip, but as maybe I won't find the time, I'll mention it here. Copenhagen is a really beautiful city. There's not any astonishing spot, but the city as a whole is really cute. I pretty loved the predominance of harmonious architecture, the main canal and its modern buildings, the imposing Christianborg, the lively, relaxed atmosphere...

Regarding Malmo, probably you've heard about it because of the Turning Torso skyscrapper. Well, honestly there is not much more to it. There are a few nice old buildings, but the old town is really, really small, and for the rest, there a few more nice modern buildings like Malmo live, the water front is OK, there is a small canal... but in general the city reminded me of Xixon, A Corunha or some of the cheap, modern and not particularly tasty areas of Toulouse... so, it's not bad, but for sure it's not too interesting.

Monday 21 August 2017

Some C# dynamic coolness

In the last days I've found some interesting things regarding the use of C# dynamic. I'll put it here.

Implementing Multiple Dispatch. The common use of dynamic is calling a method in a dynamic object. We are getting runtime single dispatch based on the object on which the method is invoked. Either the object itself if it implements IDynamicMetaObjectProvider, or the runtime via reflection, will find the method to invoke. I was not aware that this also applies when the dynamic object is used as parameter. The runtime will check its type and if several methods with the same name exist but with different argument types, it will invoke the correct one based on the runtime type. You can find a cute example here. This is pretty interesting because the runtime will use Reflection to match types with methods, doing on your behalf something that in the almighty JavaScript you would have to do on your own. By the way, this brings to my mind this explanation by Eric Lippert of the differences between using Reflection "manually" and Dynamic

Dynamic and Anonymous Types. At the time of its inception (C# 3) Anonymous Types were pretty limited. The compiler will create a class for your Anonymous Type, but you have no access to its name (so you can not do a cast), meaning that you can only access "freely" to its fields inside the method where they are created (you'll declare it as var and the compiler will use the correct type inside that method). If you return an instance of an Anonymous Object from your method, you'll be returning just an Object (you can not cast them to an inteface nor anything), so in order to access its fields you'll have to use Reflection manually.
Well, we know that dynamic will take care of using Reflection of its own (and pretty effectively thanks to caching), so we can do this:

//It's just the same if we set the return type to "dynamic" or "object" in both cases the compiler will generate a method return "Object"
//static dynamic CreateObject(int flag)
static object CreateObject(int flag)
{
  return new {Name="Francois"};
}
    
static void Main(string[] args)
{
 dynamic ob = CreateObject(0);
 Console.WriteLine(ob.Name);
}

You should notice an important limitation. Fields in Anonymous Types are internal, and when dynamic uses Reflection it plays by the rules, so it won't work if the Anonymous Type was defined in another Assembly.

Json.Net, JValue and implicit conversions. Json.NET has had an excellent dynamic support since quite a few years. This makes accessing the tree of properties in a JObject a real bargain:

var jsonString = @"{
 ""city"" : {
  ""name"": ""Toulouse"",
  ""population"" : 466000
 },
 ""otherData"" : ""aaaa"" 
}";
dynamic obj = JObject.Parse(jsonString); //returns a JObject
string cityName = obj.city.name;
Console.WriteLine("City Name: " + cityName);   

JToken (from which the different JContaine, JObject, JValue objects inherit) supports the dynamic machinery by implementing IDynamicMetaObjectProvider and returning a DynamicProxyMetaObject<JToken> (that extends DynamicMetaObject). The use of dynamic for dynamically accessing properties (or methods) of an object is what we are used to, but when you get to the last element, the "name" in my sample, you have a JValue object, so how does the assignment of a JValue to a string work?
This has quite confused me. It seems like there should be some sort of implicit conversion. Well, the thing is that DynamicMetaObject provides a BindConvert method. I've been having a fast look into the Json.NET source code and honestly, I get a bit lost with all those proxies, metaObjects and binders, but I assume somehow the BindConvert somewhere is who is doing "the magic".

Friday 18 August 2017

Covariance and Contravariance in Delegates

Delegates covariance and contravariance is a rather confusing topic and I'm not going to put any theory here, you can check any MSDN or stackoverflow response for that, I'll just put here a fast, personal reference. For an excellent approach to Variance in Programming languages, you should read this.
Short ago I talked about Converting from one delegate type to another different delegate type with the same signature. Covariance and contravariance in Delegates is a different topic, but we'll see that in one case it saves us having to do that conversion.

Since C# 2.0 covariance and contravariance applies to the rules that dictate that you can create a delegate of a certain type that points to a method of a certain return type and signature. We no longer need a perfect match between return types and the signature. You can read about it in Variance in Delegates.

What C# 4 brought to the table was covariance and contravariance between related generic delegates. Basically, now you have a relation between Func<Animal> and Func<Cat> and between Action<Cat> and Action<Animal>. It's explained in Variance in Generic and Non-Generic Delegates

I'll put some examples here for easy reference

Delegate Covariance (for return types)

If we have these custom delegate types and method:

  public delegate Animal CreateAnimalDelegate();
  public delegate Cat CreateCatDelegate();
    
  public static Cat CreateCat(){
   return new Cat();
  }

Since C# 2.0 (one MSDN article mentions 3.0, it's wrong) we can do this, bind a delegate type (returning an Animal) to a method returning a more derived type (Cat):

CreateAnimalDelegate animalCreator = CreateCat;

If we are using generic delegates we can do the same (this is not related to the out keyword introduced in C# 4), here this continues to be delegate binding.

Func<Animal> animalCreatorFunc = CreateCat;

C# 4 brought something new, you can point a variable of a certain delegate type to an instance of a delegate of a different but related type. From MSDN

In .NET Framework 4 or later you can enable implicit conversion between delegates, so that generic delegates that have different types specified by generic type parameters can be assigned to each other, if the types are inherited from each other as required by variance.

//so thanks to C# 4 I can do this assignment of a different delegate type, there is no conversion it's just type compability
Func<Cat> catCreatorFunc = CreateCat;
Func<Animal> animalCreatorFunc = catCreatorFunc;


//so in C# 4 there is type compability, but not really inheritance ("is" works, but "IsSubclassOf" does not)
Console.WriteLine("catCreatorFunc " + ((catCreatorFunc is Func<Animal>)? "IS" : "IS NOT" ) + " Func<Animal>"); //IS 
Console.WriteLine("Func<Cat> " + ((typeof(Func<Cat>).IsSubclassOf(typeof(Func<Animal>)))? "IS" : "IS NOT" ) + " Func<Animal>"); //IS NOT!!!

As you see in the example I can point a Func<Animal> to a Func<Cat>, it's as if they were in an inheritance hierarchy, but it's not really the case, cause while the is operator will tell us that Func<Cat> is a Func<Animal>, the IsSubclassOf will tell us that no inheritance exists.

All in all Covariance for return types seems pretty natural, same as we can do Animal an = new Cat(); , we can do Func<Animal> fAn = new Func<Cat>...;

Delegate Contravariance (for arguments)

Delegate Contravariance seems a bit less natural, cause basically we can do: Action<Cat> aCat = new Action<Animal>.... So it seems we are reversing the way we use type compability (a Cat is an Animal for sure, but here we seem to say that an Animal is a Cat). If we think that this applies to parameters it makes total sense. We invoke aCat passing a Cat to it. aCat points now to a function that expects an Animal, so if it receives a Cat it will behave nicely.

I'm putting here the equivalent contravariant samples for the ones above

public delegate void ManageAnimalDelegate(Animal an);
public delegate void ManageCatDelegate(Cat cat);
    
public static void ManageAnimal(Animal an){
 
}

Bind a delegate type (expecting a Cat) to a method expecting a less derived type (Animal):

ManageCatDelegate catManager = ManageAnimal;

If we are using generic delegates we can do the same (this is not related to the out keyword introduced in C# 4), here this continues to be delegate binding.

Action<Cat> catManagerAction = ManageAnimal; //this one looks a bit odd cause we are sort of doing Cat = Animal;

And what was added in C# 4

Action<Animal> animalManagerAction = ManageAnimal;
Action<Cat> catManagerAction = animalManagerAction;

Console.WriteLine("animalManagerAction " + ((animalManagerAction is Action<Cat>) ? "IS" : "IS NOT" ) + " Action<Cat>"); //IS
Console.WriteLine("Action<Animal> " + ((typeof(Action<Animal>).IsSubclassOf(typeof(Action<Cat>)))? "IS" : "IS NOT" ) + " Action<Cat>"); //IS NOT!!!

To finish this article, I'll mention that while return type covariance applies to delegates, unfortunately (in C#) it does not apply to overriden methods in a derived class (Java has support for this since a long while). For contravariant arguments, again it applies only to delegates. The feature is not available for methods in hardly any language.
To my surprise, I learn that Eiffel supports Covariance in method arguments

Thursday 17 August 2017

After the Wedding

When I first watched After the Wedding some years ago, I quite liked it, but it was last week, when watching it for second time, when I really realised how excellent this film is. Susanne Bier is such a great director and (notice that I have not watched all her films, I particularly miss Open Hearts) this is so far my favorite.

The story (co-written by Susanne) is rather imaginative and becomes more and more powerful as it develops. It's always amazed me that citizens of happy and well-functioning societies like Denmark or Sweden have such a capacity to create dark and compelling dramas (the Scandinavian Noir of Camilla Lacberg and Asa Larsson particularly delight me due to those characters living sad, complex, tormeted existences). In After the Wedding we have these 2 characters meeting again "as if by chance" after 20 years of neglect. First there's some anger, then those old feelings that will never disappear and the maturity that time gives us as such a beautiful present, will heal the pain and make things move on. This short conversation (it's not a literal transcription) describes with such sharpness how easy it is to spoil our lives:

  • - Why didn't you come back?
  • - Cause I thought you would end up following me
  • - Why didn't you follow me?
  • - Cause I thought you would come back

The most impressive moment in the film is when the husband, this strong and succesful man that had kept his terminal illness hidden from his love ones and seemed to be putting up with it so well finally crumbles. At the moment when the physical damage starts to show and the end of the "game" (our only game) becomes a too close certitude, the strong man collapses in tears, embraced to his loving wife and crying "I don't want to die". A powerful reminder of how temporal all we have, all we are, is. A reminder of how precious every second is, of how costly any unsaid word or unexpressed feeling is.

The leading actor, Mads Mikkelsen is sort of a must in most of popular Danish films. His facial expression is pretty astonishing, sometimes it's difficult to know if he's laughing, crying or both. I've recently watched another rather good film of him, The Hunt.