Wednesday, 28 December 2011

Emulate Java Enums in C#

Enums are a really useful and simple programming construct. In C, C++ and C# an enum type is little more than a set of restricted numeric values that we can assign to a variable declared as such. In C#, there are 3 main static methods that we'll need when working with enums:
Let's say we have a Planet Enum:
enum Planet{ Mercury, Venus, Earth }

  • Get the string value from an enum:
    Enum.GetName( typeof(Planet), mode)
  • Convert a string to an enum type
    Planet myPlanet = (Planet)Enum.Parse(typeof(Planet), "Venus");
  • Retrieve an array of the values of the constants in a specified enumeration. Enum.GetValues
    Planet[] planets = Enum.GetValues(typeof(Planet));

So far so good, but sometimes it's not enough. Something rather common is the need to assign some extra string values to the enum (something beyond the name itself), for example a description. The common solution in C# for this is using a custom Attribute.

That should seem enough, and it used to be, until Java got enums in version 1.4, and we learnt from there that enums could provide a much richer (and more OOP) experience. The Planets sample is really interesting and mind opening. As you can see, an enum in Java is just a normal class, with data fields, properties and methods, the only special thing is that it has a limited number of possible values. Besides the infrastructure provided by the base Enum class, the Java compiler does a nice job for us, generating a class for our enum, inheriting it from Enum and adding some methods to it like valueOf and values (diassamble the .class for your test enum and check the bytecodes, do something like: javap -v MyEnum.class > MyEnum.bytecode)

One work around in C# for simple cases would be adding behavior to a normal Enum through Extension Methods (we can also add data by placing it in the helper class containing the Extension Methods, this way avoiding the Attributes approach that I pointed out before):

public enum Planet

public class PlanetData
 public double Mass
 public double Radius

public static class PlanetHelper
 private static Dictionary planets = new Dictionary()
  {Planet.Mercury, new PlanetData(){Mass = 3.30, Radius = 2.43}},
  {Planet.Venus, new PlanetData(){Mass = 4.86, Radius = 6.05}},
  {Planet.Earth, new PlanetData(){Mass = 5.97, Radius = 6.37}}
 public static readonly double G = 6.67;
 public static double GetRadius(this Planet pl)
  return planets[pl].Radius;
 public static double GetMass(this Planet pl)
  return planets[pl].Mass;
 public static double GetSurfaceGravity(this Planet pl) 
  return G * pl.GetMass() / pl.GetRadius() * pl.GetRadius();
    public static double GetSurfaceWeight(this Planet pl, double otherMass) 
        return otherMass * pl.GetSurfaceGravity();

You can check the source here

Something like the above should be enough for most cases, but anyway, what if we want to simulate as much as possible the Java case?. Reading this StackOverflow discussion is a must

. The solution given there is pretty good, but why not to try to go the Java way and generalize as much functionality as possible to a Base class.

Before showing my solution here, I'd like to note that Java enums have another very interesting feature that I found out when reading this excellent article. One method can vary across instances, I mean, each enum value can have a different implementation for one method. Well, hopefully, in the .Net arena delegates come to our rescue, making it very simple to add that extra feature

All in all, this is what I came up with:

public abstract class AdvancedEnum
 public Enum InternalEnum;
 //notice that this Name (as Java's Name) is similar .Net's Enum.GetName()
 public string Name
   return this.InternalEnum.ToString();
 //notice that this ValueOf (as Java's ValueOf) is the equivalent to .Net's Enum.Parse()
 public static T ValueOf(string name)
  return (T)(typeof(T).GetField(name, BindingFlags.Public | BindingFlags.Static).GetValue(null));
 public static IEnumerable Values()
        //this is really weird, for some odd reason you need to use "+" instead of "."
  string tpStr = typeof(T).Name + "+" + typeof(T).Name + "Enum";
  Type tp = Type.GetType(tpStr);
  //notice that .Net warranties that values are returned in the same order as they were declared
  foreach(var item in Enum.GetValues(tp))
   yield return ValueOf(Enum.GetName( tp, item));

public class Planet: AdvancedEnum
 //naming is important here, we use as a convention that the internal enum must be named thus: className + "Enum"
 public enum PlanetEnum
 //"method" that will vary across instances
 public Action Live;
 public static readonly double G = 6.67;
 private double mass;   // in kilograms
 public double Mass
   return this.mass;
 private double radius;
 public double Radius
   return this.radius;

 private Planet(PlanetEnum internalEnum, double mass, double radius, Action liveAction)
  this.InternalEnum = internalEnum;
  this.mass = mass;
  this.radius = radius;
  this.Live = liveAction;
 public static readonly Planet MERCURY = new Planet(PlanetEnum.MERCURY, 3, 2, () => Console.WriteLine("living in Mercury is impossible for humans"));
    public static readonly Planet VENUS = new Planet (PlanetEnum.VENUS, 4, 6, () => Console.WriteLine("living in Venu would have been possible for humans milleniums ago"));
 public double GetSurfaceGravity() 
  return G * this.Mass / this.Radius * this.Radius;

You can check the source here

I plan to experiment a bit with enums in JavaScript, but for the moment, you can check this article I came across with

Monday, 26 December 2011

The Debt

The Debt is an absolutely impressive film. I had read very good critics about it, but I don't think they praised it enough. Maybe it's because it brings together many different elements that I pretty much like: the state of Israel, the Holocaust, Berlin, Revenge...

But above all this is a film about lying and fleeing. A past lie shapes the life of 3 (well, many more) Israeli who deal with it very differently. It's a justified lie, a lie I think I would have been happy to tell and would have no had problems to live with, but that's not the same for one of the characters, who has been unable to deal with it, being haunted with it for the ensuing 30 years of his ruined life. In the end, that allegedly buried dramatic event of the past is about to come back to life, casting its shadow over a fairly increased "public", and the 3 characters will try to come to terms with it following very different approaches.

These 30 years have been a continuous flight for our 3 characters, and also for the Nazi butcher. Now they'll have to decide whether to continue the flight or put a painful end to it. The same doubts they were confronted with in an old flat in Berlin 30 years ago will assault them now in Tel Aviv and in a Ukrainian hospital.

Not much more to add, just to remark how excellent the interpretations by both Jessica Chastain and Helen Mirren are. That's all, now just go and watch it!

Wednesday, 14 December 2011

Some interesting stuff

Just a compilation of links of interesting programming stuff that I've come across with in the last days and that I would like to note down for future reference

  • I think it's commonly accepted that C# is a much more expressive language than Java, I've already written indirectly about it in some other posts, but given that I try to be as language agnostic as possible, and try to learn lessons from all languages I know, I think it's good to acknowledge some of the strong points of Java. I don't miss Anonymous classes in C#, but Java class-like enums are something that I've been pretty jealous of since I first heard about them, and the Method return type covariance really caught me by surprise.
  • Continuing with Java, I was rather interested to see how the long awaited invokedynamic thing has improved the overall Java experience. Long in short, it's a great addition to the JVM platform, but for the Java language itself it adds quite little. If you were expecting something similar to C#'s dynamic keyword, forget about it. However, contrary to C# dynamic that just comes down to a lot of compiler magic, the JVM has been enhanced to deal with invokedynamic. This old post is a great source of information.

    The biggest changes in Java 7 are not related to the Java language at all. Sure, there's the "project coin" enhancements to the Java language, which add some exception-handling shortcuts, new literals for numbers, arrays, hashes, the oft-requested "strings in switch" support, and a few other things. But they're modest incremental changes; the real revolution is at the JVM and JDK level.
  • After reading this excellent interview in InfoQ discussing the new Groovy candies, one of the things that really caught my eye is passing closures to annotations. That would be the equivalent of passing delegates to attributes in the .Net world. This feature does not exist, but it's interesting to see how some people were requesting it some time ago. The AST transforms seem quite in line with some of the things that Roslyn has to offer or with Boo's Syntactic Macros
  • As I said in a recent post, time seems to fly, and much more when we talk about technology. Last time I had tried to create a bootable flash drive it was still rather troublesome, so when last week I stumbled upon this site and found out how easy it's to create a multiboot flash drive, I felt delighted.

Monday, 12 December 2011

Atomised/The Elementary Particles

Another excellent German film. At first sight this hilarious work could seem quite apart from my common tastes (horror, dystopias, social unrest...) but I've had a really enjoyable time with it, well, in fact it ends up being a very human film, maybe it's because I'm right in the age group to get some sort of identification (hey, don't take me wrong, I'm not such a loser as Bruno)

This is the story of two brothers with very different lives: Michael is a scientific genius, Bruno is a frustrated everything (teacher, writer, father, play boy...) but a common problem, their (lack of) sexuality, and quite different approaches to tackle it (remove the need for sex by developing cloning techniques vs harass teenager students and join a free love camp...) Bruno (the frustrated writer, by the way he portrayed Baader in The Baader Meinhof Complex) has the main role in this film, as the funniest moments (and also the harshest ones) gravitate around his pathetic adventures (his racist prejudices, his bonobo like attitude, his dramatic attempts to gain other's simpathy...). Maybe his character was so fun to me cause in some of his actions I could try to put faces that I know in real life :-)

Be warned that there's more to this film that all this fun, while the 2 first thirds of the film will mainly make you laugh like hell, the last part will make you reflect about the tough situation presented there and about life in general, mainly if you're at that age when you still see yourself too young for some "für immer" decisions, but too old to continue wandering aimlessly

A must see film that I would leave in store to ease a bad day

Tuesday, 6 December 2011

And time goes by

I think I tend to be rather aware of how fast time passes, how our precious minutes get consumed, but even with this in mind, sometimes something comes up that makes me even more conscious of this fact.

Yesterday, one piece of news that probably will have gone unnoticed for many people (that increases that feeling of time running away), clearly reminded me of it. Napster is over. Napster, the first P2P application, the one that opened a new world of unlimited access to music to many of us, is no more. I remember getting late to a Saturday night meeting with friends cause I was eagerly waiting to see if I managed to finish the download of a much desired disc (through my old good 56 kbits modem with flat rate connection only from 18:00...). It's been 11 years since that, and many, many things have changed. Drawing up from Napster's success many other P2P sharing applications flourished (and rapidly faded away): Kazaa, WinMX, AudioGalaxy, eMule... BitTorrent seems to be one of the few that is still in pretty good shape.

I would say we've almost reached the point where we're not aware of how things (in the technological world, unfortunately other areas have not nearly seen this level of evolution) have improved, how now we take for granted things that just 5 years ago were unthinkable. We're in the middle of an Accelerating Change, just think for a moment:

  • Online video (YouTube, DailyMotion and so on...) in 2003 the common perception would be that there would be no bandwidth enough (not at home, but in the internet itself) for transmitting all those bytes.
  • Free WiFi in almost every coffee shop in town (well, I'm talking about my town, oddly enough, it's harder to find a Free WiFi in London or Berlin that in Xixón)
  • Dual core 1GHz processing monsters weighting just 200 grams and living in your pocket. It's funny when I look to the heavy and bulky old desktop PC lying in a corner of my room, with 392 MBs of RAM and a 800MHz processor and think of how well it served me as my main Programming and "multimedia" platform until 8 years ago.
  • With those 1 and 2 TBs external disks sitting on your desktop, do you remember the last time you burnt a data DVD? Did you ever use your old PCs as "storage server" in your local network? It seems like an odd occurrence now
  • Do you remember those times when owning a laptop was only for wealthy guys or for the "important people" of the company?
  • Internet everywhere thanks to affordable 3G data connections. This is something that left me astonished 2 months ago when I switched to my new Mobile phone operator. They have a monthly flat rate data plan (even for pre pay users like me) for just 9 euros. I don't need that service, it would be useful to me only when I'm abroad (I guess that's one of the pending things that we'll see changing in a short time, flat rate data access everywhere, at least in Europe) but if you need it, it's rather affordable.
  • GIS for the massess!!! Google Maps, Bing... and one million applications based on them
  • Home bandwidth. I've got now a 15 Mbits (download) connection at home. This is how my bandwidth (download) has evolved ever since I have internet at home:
    • 2000: 56 Kbits Modem (I think there's a generational gap between those who are familiar with the noise of a Modem when dialing and those who aren't)
    • 2001: 128 Kbits with my Cable operator (the only one I've had so far)
    • 2004 (August), 160 Kbits
    • 2005 (May), 640 Kbits
    • 2007 (February), 1Mbit
    • 2009 (June), 10 Mbits
    • 2011 (May), 15 Mbits (not an advertisement trick, you can see below that you really get that speed )

The other day I was chatting with a friend (a C++ guru, not a "humanities" guy) and he told me with his brand new smartphone on his had "I'm fed up with 3G, it's so slow that I have to use WiFi when I'm at home". I was astonished, we've grown so accustomed to the marvels of technology that we expect more and more from it, and dare to think that 3G should be as fast as our home WiFi!!!

I can't close this post without saying a clear and loud THANKS NAPSTER!!!

Friday, 2 December 2011

FIC Xixón 2011

One more year has passed, and this odd Autumn (almost no rain, summer like temperatures... shit, I love my normal dark, rainy Asturian autumns... bloody climate change) has brought us a new edition of Xixón's Film Festival. This year I could attend to 9 films, and my perception was pretty good, there are only 2 of them (well, maybe just 1) that were not worth my time (and I already suspected these films would not fit my taste, but had nothing more to choose for that session), all the others ranged from entertaining to excellent.

  • Viva Riva by Djo Tunda Wa Munga, Congo/France/Belgium (sounds like colonization revival :-), Rellumes section (Friday 2011/11/18)
    I think this is my first African movie, and it's pretty good. A story full of violence, sex and action, Kinhasa has almost run out of gas, and that turns Riva, a gas smuggler, into one of the big men of the city. He chases after an African beauty, and a bunch of ruthless criminals chase after him and his gas. It's interesting to see how even in these times of global everything... attitudes towards, sex, violence, money, and life in general are still rather different depending of our geographical location.
  • Take Shelter by Jeff Nichols, USA, Official competition (Saturday 2011/11/19)
    Excellent film. Some people could had been misled to think that this would be one more apocalyptic film (that's neither good nor bad for me, there are some "end of the world scenario" films that I really like), but not, this is not one of those films. Well, in fact maybe it is, but a different kind of apocalypsis. It's not a natural disaster or man made threat what the characters are really presented with, but a personal disaster, one of the worse that one can imagine, losing control of your mind and being aware of it. The hell descends upon an Ohio family when the householder, whose mother has been suffering from schizofrenia since her thirties, starts to suffer from delusions, paranoia and terrible nightmares. There's a very interesting situation here, while he's pretty aware of the severity of his case and the high chances of him going crazy, he just can't avoid to carry out some plans based on what his delusions and paranoias tell him. I would consider this a very harsh film, a drama that almost turns into horror, internal horror. It grows in intensity as it moves forward, reaching some devastating moment at the end. A must see film.
  • Unfortunately I could not attend to any film on Sunday, as I was selected (it's a draw where any Asturian (well, any Spaniard) older than 18 can be selected, no volunteers here...) to waste the whole day working for the electoral system (you're seized by democracy to collaborate with it under threat of prison if you refuse, no matter if you're an Anarchist or are fed up with their System)
  • Essential Killing by Jerzy Skolimowski, Poland/Norway/Ireland/Hungary, Generos Mutantes section (Monday 2011/11/21)
    Rather interesting film. It's not the masterpice that the guy that introduced the film praised, but certainly a rather good one. One Taliban is taken from Afghanistan to Europe and manages to scape, wandering through a forest in in the middle of Polish winter. A harsh depiction of the fight for survival in a very hostile environment enriched by the empressive natural landscapes (the Afghan mountains first and the European forest then). Some people try to do a sociopolitical reading of the film, the director has denied it, and I'm on his side, I don't think he would have chosen a Taliban shithead as main character if he wanted people to feel identified with him.
  • Faust by Alexander Sokurov, Russia, Official section (Tuesday 2011/11/22)
    Long in short, I didn't like it. Well, I quite liked some visual passages, but the development of the story was quite uninteresting. I've not read the book by Goethe, but given its masterpiece status I'd like to think that a much better film adaptation could have been done. During the first hour I had to strive to not fall asleep, then things got better, but it was just only the excitement of thinking how the end was getting closer...
  • Hors Satan by Bruno Dumont, France, Official section (Wednesday 2011/11/23)
    Terribly boring film, the plot lacks of any interest (well, there's hardly any story being told) and it's just a few sequences along the film mixing violence, sex and oddity what prevents you from falling asleep. By the way, this film presents us with one of the most disgusting sex scenes that I've seen in a long while...
  • Punk's not dead by Vladimir Blazevski, Macedonia, Rellumes section (Thursday 2011/11/24)
    I pretty much enjoyed this my first Macedonian film ever. The synopsis really caught my attention, some 40 something punks in the ramshake city of Skojpe intending to relive their old band. Once in the cinema the story turned out to be pretty good, many fun moments, and an excellent way to show us different tough aspects of the life in Macedonia (that can apply to a good part of the ex-Yugoslavia). The director could have slapped us with each of those aspects: ethnic conflicts, lives and social networks broken by the Western sponsorized civil war, alienation, escape from reality through fucking chemicals... but instead, he preferred to show all this in a soft way, more like a pinch, but one of those which stinging remains with you for a long while. This was the only "meeting with the director" session I could attend this year, and it was outstanding. Vladimir Blazevski gave an introduction that really shocked me, he told us how special and touching this film had been for him, after a 17 year hiatus due to the state of shock in which the break up of Yugoslavia, the fall of the socialist system and the devastating civil war had left him. Once the film finished and excellent discussion with him followed. There he explained (slowly, with a discourse full of details and in a sad and reflective voice) that he had never been related to the Punk counterculture, but that he chose it for this film because of their condition of outsiders, of people that do not seem to fit... just how he felt after Western democracies and the Vatican decided to destroy Yugoslavia.
  • The Stoker by Alexei Balabanov, Russia, Rellumes section (Friday 2011/11/25)
    One entertaining film by Balabanov, indeed I liked it quite more than his other 2 films that I'd previously watched. This said, I don't understand why he has gained the cult status that he seems to enjoy, to me he does entertaining violent films, just that, nothing more. At least this time he shows signs of some social awareness, thing that I absolutely missed in his stupid "Russian Rambo in Chechnya" (War) film. This film (same as Cargo 200) reflects the state of disgrace in which Russia lives after the fall of the Communist State, but I don't think Balabanov has any kind of political intention (OK, yes, I have to admit it, I feel some aversion for this guy because of his stupid antiChechen film)
  • Michael by Markus Schleinzer, Austria, Official section (Saturday 2011/11/26)
    A great surprise. Based on the synopsis I had many doubts about this film, but it was the one that better suited my schedule. It could be a masterpiece or it could be an unbearable "experimental" piece, hopefully it turned out to be an excellent film. Based on a very harsh situation (a kid that's been kidnapped for year by a correct, intrascendent clerk that happens to be a pedophile) the director creates a very convincing work, where while avoiding explicit displays of "horror" he shows enough to make us feel uncomfortable and keep us glued to the screen. There's a very interesting portrait of another terrible situation, members of a family dividing the properties of their deceased loved one, as a fundamental part of the process of getting over the tragedy.
  • Miss Bala by Gerardo Naranjo, Mexico, Géneros Mutantes section (Saturday 2011/11/26)
    An excellent finale for this edition. This is a very convincing and well done radiography of Mexican society, so you know what to expect, violence, gratuitous violence, at any moment, by any (no) reason and exerted by anyone. And also, corruption, plain corruption pervading it all, anyone, any social construct... a broken society suffering a sort of civil war. If it makes it to normal cinemas, go and watch it!
You can check my reviews of past editions here and here.