Tuesday, 6 August 2013

Maniac

I don't feel much like writing a post now, but after watching this masterpiece I feel compelled to share it with anyone reading this blog. Maniac is one of the best horror films I've watched in a long while. It's extreme, extreme, extreme, utterly extreme... Though set in Los Angeles and starred by North American actors, you could somehow associate it to the New French Extremity school (indeed the director is French).

The story is nothing new, a disturbed young man with a repressed sexuality (due to a trauma from his childhood owing to his mother's unrepressed sexuality) turns into a serial killer. Sure you can think of several films revolving around the same idea, but this one is spiced by some brilliant elements, like being entirely shot from the Point of View of the murderer, the mannequins that give it a feel of arty and "modern horror", and especially the sheer brutality of some of its moments.

Really, this is an absolutely must see for anyone into horror films, but be warned that many people could find it too hard. Indeed, I for one would say there's more blood on screen than necessary, and the last sequence of the film was quite unnecessary (a gore feast that adds no value at all). But well, perfection is the biggest of horrors.... By the way, this is the remake of a film of the 80's, so probably I should also give it a try.

Saturday, 3 August 2013

Multiple Inheritance in C#

From the many features being added to Java 8, there's one that has really caught my eye, Default Interface Implementation aka Defender Methods (the other ones are really necessary stuff, but nothing out of the ordinary, as it's stuff that should have been in the language many years ago).

The main motivation for these Default methods is the same as for Extension Methods in C#, allowing you to add methods to an interface without breaking existing code. Let's think in C# and the pre-Linq times. You had an IEnumerable interface, and felt the need to add to it methods like "Contains, All, Any, Skin, Take...". Well, if you just add those methods, all your existing classes implementing IEnumerable would need to be updated to add an implementation of those methods there... well, quite a hard job. The solution to this in C# were Extension Methods. In Java they were about to mimic this same approach (and indeed you'll still find old references to "Java Extension Methods") but in the end they opted for a much more powerful one, Default Interfaces.

public interface SimpleInterface {
public void doSomeWork();
//A default method in the interface created using 'default' keyword
default public void doSomeOtherWork(){
System.out.println('DoSomeOtherWork implementation in the interface');

You've always been able to implement multiple interfaces, now they're adding behaviour to interfaces, so this winds up in you being able to inherit behaviour from multiple "places"!!!

Extension Methods in C# also adds behaviour to interfaces, and as such you also get a sort of Multiple Inheritance, but in a quite more "second class" limited way. Extension Methods are just a compiler artifact and the method resolution is done at compile time, so you lose the runtime magic of polymorphism-overriding-vTables. When you extend an existing Interface with new methods, if then a derived class implements one of those extra methods, polymorphism won't work to invoke that overriden method. Let's see an example:


public interface IPerson
{
 string Name{get;set;}
 string SayHello();
}

public static class IPersonExtensions
{
 public static string SayBye(this IPerson person)
 {
  return person.Name + " says Bye from Extension Method";
 }
}

public class Person:IPerson
{
 public string Name {get;set;}
 public Person(string name)
 {
  this.Name = name;
 }
 
 public string SayHello()
 {
  return this.Name + " says Hello";
 }
 public string SayBye()
 {
  return this.Name + " says Bye";
 }
}



public class Program
{
 public static void Main()
 {
  //the extension method is good to add a SayBye to the IPerson interface
  //but as a compile time artifact, it will not take into account if the implementing class has "overriden" it
  IPerson p1 = new Person("Iyan");
  Console.WriteLine(p1.SayBye()); //writes "says Bye from Extension Method"
  
  Person p2 = p1 as Person;
  Console.WriteLine(p2.SayBye()); //writes "says Bye"
 }
}

In the example above, the IPerson interface has been extended with an additional method SayBye through the IPersonExtensions static class. Then the Person class tries to override SayBye with its own implementation, but polymorphism won't work when it's invoked in a Person object via IPerson, and the IPerson implementation in the Extension Method will be used rather than the one in Person.

Other limitation of Extension Methods is that they are not visible via Reflection, I mean, if you call Type.GetMethodInfos() it won't return in that list those methods that could be accessed in that type via Extension Methods. As a consequence of this, they don't play well with dynamic either when you expect that dynamic resolution to be done through Reflection. You'll find more information on this here and here

With all this in mind, I decided to simulate this "Multiple Inheritance of Behaviour" in C#. The idea is simple and effective, though not much wrist friendly. For each interface whom you'd like to add behavior you create a class that implements the interface and contains those "default methods", and then, for your normal classes implementing that interface, you'll add a reference to that class for the default implementation, and for those methods for which you don't want to override the default implementation, you just delegate calls to that reference.

public interface IValidable
{
 bool AmIValid();
}

public interface IPersistable
{
 string Persist();
 
 int EstimateTimeForFullPersist();
}

public class DefaultValidable: IValidable
{
 //just one single method, no calls to other methods in the class, so no need for an Implementer field
 public bool AmIValid()
 {
  return this.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance).All(PropertyInfo => PropertyInfo.GetValue(this) != null);
 }
}

public class DefaultPersistable: IPersistable
{
 public IPersistable Implementer { get; set; }
 public DefaultPersistable()
 {
  this.Implementer = this;
 }
 
 public string Persist()
 {
  //notice how we have to use [this.Implementer.Estimate] here to allow method overriding to work,
  //cause using [this.Estimate] would invoke the Default (NotImplementedException) one.
  if (this.Implementer.EstimateTimeForFullPersist() > 1500)
   return this.ToString();
  else
  {
   //complex logic here
   return "this is the result of a complex logic";
  }
 }
 
 public int EstimateTimeForFullPersist()
 {
  throw new NotImplementedException();
 }
}

public class Book: IValidable, IPersistable
{
 protected IValidable ValidableImplementation { get; set; }
 protected IPersistable PersistableImplementation { get; set; }
 
 public Book(DefaultValidable validableImp, DefaultPersistable persistableImp)
 {
  this.ValidableImplementation = validableImp;
  this.PersistableImplementation = persistableImp;
 }
 
 public bool AmIValid()
 {
  //delegate to default implementation
  return this.ValidableImplementation.AmIValid();
 }

 public string Persist()
 {
  //delegate to default implementation
  return this.PersistableImplementation.Persist();
 }
 
 public int EstimateTimeForFullPersist()
 {
  //do not delegate to default implementation, "override" it
  return 50;
 }
}

public class Program
{
 public static void Main()
 {
  DefaultPersistable defPersistable = new DefaultPersistable();
  Book b = new Book(new DefaultValidable(), defPersistable);
  defPersistable.Implementer = b;
  
  Console.WriteLine("Is the Book valid: " + b.AmIValid().ToString());
  Console.WriteLine("Book.Persist: " + b.Persist());
 }
}

Looking at the implementation above you'll notice that the code is more straightforward for DefaultValidable than for DefaultPersistable. No defaul method in DefaultValidable invokes other methods in the interface, while in DefaultPersistable the Persist method invokes EstimateTimeForFullPersist, which means that in order to invoke the correct implementation if EstimateTimeForFullPersis has been overriden, we have to use the Implementer reference for those invokations.

You should also notice that while the above technique allows "Multiple Inheritance of Behavior" it does not address the real motivation of Default Methods in Java, extending the contract of an existing interface with new methods without breaking existing code. You still need to resort to Extension Methods in C# for that.

All this has reminded me of an interesting post I read months ago about using ES6 proxies as a way to implement multiple inheritance in JavaScript. The idea is pretty interesting, but I see an important flaw, the instanceof operator won't work with the "base classes". Applying instanceof to the proxy object will tell you that it's neither an instance of base1 or base2. This could be fixed if instanceof were also interceptable in the proxy, but seems like (at least in the current proposal) it's not.

By the way, as it's somehow related to this article, I'll reference here my write up about Extension Methods and Mixins/Traits from last year.

Thursday, 1 August 2013

Scandinavian Crimes

My reading habits (technical or social stuff aside) are pretty lame, with an average I guess of 3 books per year. Moreover, I'm not into the classics or anything of the sorts, and in the last years almost all the literature that I've read has been Scandinavian crime novels (yeah, pretty trendy), and I have to say I really love this "literary school". I started off with Stieg Larsson (yes, I got totally hooked to the Millennium Trilogy, even when I find some failing points in it) and then went on to deeply enjoy with Asa Larsson and Camilla Läckberg.

These to Swedish ladies are really excellent writers. Their plots are pretty good, but what I like most of them (and that I think is the reason for having got so trapped by their novels) is the tortured characters and their outstanding emotional depictions. These novels are inhabited by tormented souls, people that apparently live a normal life, but that to a greater or lesser extend live surrounded by (their own) phantoms, haunted by remorse, tortured by some old bad decisions that have left a bitter taste in their mouths, a taste of failure and incompleteness. Sometimes the source of all this discomfort are large tragedies, but for other characters it's a concatenation of small inconveniences what makes up their personal landscape of desolation. A vast, wild (and snow covered, it could not be otherwise) landscape, overcast skies, deep lonely forests or small communities where the permanent gossip isolates those that consider themselves in the losers side... that's the another essential part of these novels.

In the last months I've read "The Hypnotist" (pretty good, I'm longing to get my hands on the film adaptation) and Jo Nesbo's "The Leopard". The Leopard is a delightful book, I liked it quite more than "The Snowman" that I read last year. The emotional component in this book is quite less present than in Asa Larsson or Camilla Läckberg (even when the main character, Harry Hole is a fucked up man lashed by addiction and guiltiness), but on the other side the plot is quite more complex and twisted, and will keep you glued to its pages since the first line.

Harry Hole makes some excellent reflections on the human nature (that he happens to be not too fond of) and among them, I'd took note of this paragraph:

That's how banal we are. We believe because we want to believe. In gods, because that dulls the fear of death. In love, because it enhances the notion of life.

Pondering on these books and authors a bit more, I think my winner is Asa Larsson, mainly due to the soft fantastic element that she adds to novels like "The Black Path" (my favourite) or "Until Thy Wrath be Past". This component is unique (I think) when compared to other authors and I would say is the cherry on top of a carefully cooked delicious cake.

Saturday, 27 July 2013

JavaScript Function Overloading

Somehow I recently came across this old post by John Resign about Method Overloading in JavaScript. Just a few lines of beautiful JavaScript code, but I don't like much the idea of wrapping one function over another. Also, his sample applies only to "methods", so I decided to write my own, rather different, implementation, that applies to functions, uses my beloved technique of adding metadata and "methods" to functions, and allows for the removal of overloads.

I've uploaded it here.

//prompted by: http://ejohn.org/blog/javascript-method-overloading/

//baseFn: function that will be used when the overloaded function is invoked with a non matching number of parameters
function overload(baseFn /*, overload1, overload2...*/){
 //returns an overload aware function
 function buildOverload(baseFn){
  var overloads = {
   "default": baseFn
  };
  overloads[baseFn.length] = baseFn;
  var overloadedFn = function(){
   if (!overloads[arguments.length])
    return overloads.default.apply(this, arguments);
   else
    return overloads[arguments.length].apply(this, arguments);
  };
  overloadedFn.overloaded = true;
  overloadedFn.add = function(fn){
   overloads[fn.length] = fn;
  };
  overloadedFn.remove = function(fnLength){
   delete overloads[fnLength];
  };
  return overloadedFn;
 };

 baseFn = baseFn || function(){};

 if (!baseFn.overloaded)
  baseFn = buildOverload(baseFn);
 overloads = [].slice.call(arguments, 1);//obtain array from arguments pseudoarray removing the first element 
 for(var i=0; i≶overloads.length; i++){
  baseFn.add(overloads[i]);
 } 
 return baseFn;
}

if (typeof module !== "undefined" && module.exports){
 exports.overload = overload;
}


Notice that both John's implementation and my implementation base the dispatch mechanism in the number of parameters received by the function. Last year I wrote about multimethods in JavaScript, that though related, is quite different. In this other case your function also has several implementations (so it's overloaded), but the dispatch is based on the "type" of the parameters.
My basic Multimethods implementation just will throw an error if not "full match" is found, that is, both the number of parameters and the exact type match (if the exact type does not match it won't consider as valid an overload where a base type exists). So well, I guess I should think about writing an improved version...

Monday, 22 July 2013

The Devil's Advocate

Yesterday I watched again The Devil's Advocate, one of my all times favourite films. The movie has an interesting plot and develops pretty well over it's first 2 hours, but it's the last 10 minutes what turn it into a masterpiece.

Al Pacino's anti religious speech left me speechless the first time I watched this film, you're before a Hollywood production and suddenly you stumble upon one of the fiercest and most intelligent attacks on religion that you can imagine!

I've found the discourse here:

John Milton: I want you to be yourself. Y'know, boy, guilt is like a bag of ing bricks. All you gotta do is set it down.....Who are you carrying all those bricks for anyway? God? Is that it? God? Well, I'll tell ya, lemme give you a little inside information about God. God likes to watch. He's a prankster. Think about it. He gives man instincts! He gives this extraordinary gift and then--what does he do? I swear--for his own amusement--his own private cosmic gag reel--he sets the rules in opposition. It's the goof of all time! Look. But don't touch! Touch. But don't taste! Taste. Don't swallow! [laughs] And while you're jumping from one foot to the next, he's laughing his sick ing ass off!! He's a tight ass, he's a sadist, he's an absentee landlord!! Worship that never!

Kevin: Better to reign in Hell than serve in Heaven, is that it?

Milton: Why not? I'm here on the ground with my nose in it since the whole thing began! [screaming] I've nurtured every sensation Man has been inspired to have! I cared about what he wanted and I never judged him. Why? Because I never rejected him. In spite of all his imperfections, I'm a fan of man!! [Calms] I'm a humanist. Maybe the last humanist. Who, in their right mind, Kevin, could possibly deny the 20th century was entirely mine? All of it, Kevin, all of it! Mine! I'm peaking here! It's my time now. It's our time.

wow... can you picture yourself in Keanu Reeve's (Kevin) shoes? Al Pacino (John Milton) spitting such words of wisdom while a nude Scandinavian Goddess (yes, I've got sort of an obsession with this "Valkiria") tries to push you into bed?

The whole performance by Al Pacino is superb, I can't think of any way to improve the way he plays the polyglot, ultra smart, party minded, sleepless, handsome devil "business leader".

By the way, Hocico used this speech as a sampler, and the result was excellent..

Sunday, 21 July 2013

The Odd Case of the Dual-core Netbook

I purchased a second hand laptop a few weeks ago (yes, it may sound like a bit retro/vintage thing to buy a netbook now when they've almost gone away... but let's say it took me a while to find a situation where a netbook could be useful to me).
It's a Vaio VPCW12J1E, and first of all, in case anyone is contemplating to get one, I want to state here that Lubuntu (light Ubuntu) works like a charm on this machine. WiFi will work nicely out of the box, sound card, everything, even the key shortcuts for brightness and sound! and it's absolutely astonishing to see how little memory it needs, really amazing, much more when we've got used to such resource hungry crappy software like Android...

This netbook already came with Windows 7 starter, which works pretty horribly performace wise, but it's not a Windows thing itself, it's something with the tons of (unnecessary) software that retailers add to it...
Well, the thing is that to my surprise Windows 7 tells me that I have a dual-core processor, which was quite unexpected cause it seemed to me that most netbooks (and more from that time, 2009) are single-core machines.

Windows Device Manager:

Windows Task Manager:

However, the Lubuntu Task Manager (lxtaskmanager) tells me it's a Single Core machine, pretty odd:

As you can see from one of the screenshots above, this is an Atom N280 processor, and as I suspected, Wikipedia tells us it's a Single-core Processor, so WTF? After a few searches the answer revealed itself in some forum, it's a Hyper-threading (HTT) thing!

Hyper-threading, wow, that brings up some old memories. A long while ago I was pretty much into how hardware works, and I quite well remember having printed and read some material about this "Virtual MultiProcessor" kind of thing, back in early summer 2002 (at that time the Itanium also seemed like the new king of the party) In a few years Multi-core processors became common place, and the Hyper-threading thing just was no more (or at least that's what I wrongly thought).
In short (not just to save space, but because I have a minimum knowledge about this topic), in an Hyper-threading processor some units in the processor core are duplicated (but not all of them, so it's very far from being a Multi-core/Multi-processsor), so that under some conditions it offers some sort of multiprocessing. The Operating System will see it as 2 cores, and will schedule 2 threads simultaneously, and then depending on the instructions/state of the processor, sometimes some sort of parallelism will happen.

This has made me muse over concepts I had almost forgotten, like the Processor Pipeline and Superscalar processors. Well Superscalar and Hyper-threading seem quite related, as in both cases some functional units in the processor are duplicated in order to provide some form of parallelism. This wikipedia entry is quite elightening. My understanding then is that with superscalar techniques (the attempt of) parallelism happens with instructions belonging to the same thread/process, and without any knowledge on the OS side, while with Hyper-threading, this (attempt of) parallelism happens between different threads/processes, and needs of the OS taking part on it.

This thing of Lubuntu's Task Manager showing only 1 processor made me wonder whether my OS would have the Hyper-threading support enabled, so I did a couple of checks to verify that HTT support was enabled:

  • sudo dmidecode

    where the status: Populated, Enabled means that HTT is enabled
  • run top and press the "1" key, so that processors are listed (Cpu0 and Cpu1):

This last check was particularly odd. As HTT is a very limited form of parallelism, it would appear fine to me if Linux decided to show me a single processor, but the fact of top displaying 2 processors and the Task Manager displaing 1, is confusing to say the least

Thursday, 11 July 2013

Some Thoughts on Iterator.Remove

In my last article I mentioned that Java's Itearator<>T> features a remove method that is missing in .Net's IEnumerator<T>. Such difference is a bit surprising, and at first thought it seemed to me that it made Java Iterators more powerful that .Net Enumerators. Well, after giving it a second thought, it strikes me that such remove method should not be there.

Why am I saying this? Well, first I would recommend reading this good discussion, even when it's not much related to what I'm going to discuss below. So, in principle the idea looks good, as removing while iterating is problematic, why not add such functionality to the class that already takes care of the iteration? This class has deep knowledge of the class being iterated, enough knowledge to allow it to take the necessary measures so that a removal operation does not break the iteration. So far so good, so what's the problem?

  • First of all, now the Iterator interface has 2 capabilities (responsibilities), iterating and removing while iterating, when probably some classes just need the first one, iterating. So, I would prefer 2 interfaces here, something like Iterator (that just iterates) and something like RemoveEnabledIterator.
  • You could say that if you're not happy with current Iterator, you can just create your own ReadOnlyIterator/Iterable interface and use it rather than Iterator/Iterable in those classes that don't allow the removal. There's a huge problem here, that Iterator is a fundamental class in the Java language, as Iterable-Iterator form the basis for the enhanced for loop (for : ). This means that with the current design, if you want to be able to iterate one collection with (for : ) it has to implement Iterable, so you'll have to define an Iterator, and you'll be forced to implement a remove method in it. OK, some people will say that you're not forced, as the documentation states that the remove method is an optional operation. Problem is that this "optional" thing seems a bit messy to me, it just means that you can implement it or throw an UnsupportedOperationException, which entails that consumers of an Iterator can not assume that your Iterator supports remove and they'll expect to see it cleary explained in your documentation. This question provides some good information.

So, all in all, I reckon I'm quite more happy with .Net's IEnumerable-IEnumerator pair.