Tuesday, 25 February 2014

Prisoners

I found myself with this film playing on my laptop with quite little information about it and unclear expectations. It was just one of the titles that showed up in some of my typical early year seachs: "Best Thriller films 201X", "Best Drama films 201X", "Best Horror films 201X"...

It didn't start too well. The archetypical American family: religious, living in one of those neighbourhoods of single-family houses where you need your car even to go to buy the newspaper, with a father (a Hugh Jackman very concerned about getting ready for the end of the world) that has just taught his teenager son (very concerned about how to buy his first car) to hunt a deer... Well, you know that I'm a proud European (even more now that I'm living in France), so the "American Way of Life" is almost that alien and disturbing to me as the "Saudi Way of Life". OK, I have to say that this family are close friends with an AfroAmerican family, which is not a so "American thing", as however much they now have a black president (a black president that continues to invade countries under the pretext of "peace and democracy" as aggressively as his "WASP" predecessors did), my understanding is that both communities continue to be seriously disconnected (and what to say of the "Brown" (latin) community...) Well, enough hate for the USA for today, let's focus on the film.

So, both families come together for Thanksgiving day (yet more American stuff...) and during the afternoon their 2 little girls get abducted. Not satisfied with how the police is carrying out the investigation, one of the 2 fathers (Hugh Jackman) decides to put matters in his own hands, but the whole thing goes out of control and the victim turns into monster. I won't give more details, just will say that as the film draws on, what could have been just one more entertaining film turns into an excellent one. The plot develops masterfully and unexpectedly, facing us with the moral struggles of 2 tortuous souls.

Once finished I felt prompted to check what other films this director had worked on, finding out that this man is the genius that directed Incendies and Polytechnique 2 absolutely breathtaking works. Indeed, one can find some common ground between Prisoners and Incendies, being the religious factor the most notable to me. From the "War for God" in Incendies (that sequence when a Christian Lebanese militia executes a group of innocent muslims and we can see an image of Virgin Mary glued on the machine gun of one of the executioners is one of the best representations of human misery that I've come across in a long while), to the "War against God" of the murderers in Prisoners, intending to make people to lose their faith through the exposure to a horror and injustice that a benevolent God would never allow.

The DVD release of this film was announced on many French kiosks last week. In the advertisement they compared it to Seven. Well, I wouldn't have come up with such relation on my own, but indeed it's not misguided, though Seven remains at an upper level that very few films can reach.

Saturday, 15 February 2014

Perl is Cool 2, Reflection

Perl sports some excellent reflection capabilities, indeed it does not need a Reflection API as Reflection is built into the Language itself. Let's take a fast look at some of these features:

eval

Same as JavaScript, Perl provides an eval function that allows for the compilation of new code at runtime. You could be tempted to use it in many occasions (creating new Objects, accessing Methods or Data Fields known at runtime), but most times this is unnecessary and you can use a more straightforward approach.

Get Object Type

You can get the type of an object (the Package used to bless a reference) with ref.

Object Creation

Notice that ref returns a string (in contrast with .Net or Java, where .GetType or .getClass return an instance of Type or Class respectively, a special type that exists just for that, representing types). Being just a string could seem to pose some limitations, but it doesn't, cause perl allows you to use a string to reference a package/class and invoke methods on it. This means that you can create objects based on a string provided at runtime:

my $type = "Person";
$type->New("Iyan");

If you're writing Old School Object Oriented Perl you're using just that in your constructors to bless your references:

sub Person{
my ($class, $name) = @_;
my $self = {
name => $name
};
bless $self, $class;
return $self;
...
Method Invokation

Likewise, you can use a string to invoke a method

my $methodName = "SayHi";
$p1->$methodName();

Obviously you can combine the 2 features above, doing something like this:

my $class = "Person";
say $class->New("Anton")->$method();
Check whether an object has a method
You can do this directly on your "class instances" by means of UNIVERSAL::can , or by checking if the corresponding module contains that function:
say "p1 " . ($p1->can("SayHi") ? "CAN" : "CAN NOT") . " sayHi";

say "Person " .  (defined(Person::SayHi) ? "CAN" : "CAN NOT") . " SayHi";
Get Current Method Name
You can use the caller function to traverse the current stack. It returns an array of strings, one of the most useful uses is doing a print (caller(0))[3]; to get the name of the currently executing function.

Get Package Name
You can get the name of the current module with __PACKAGE__

Get File Name
You can get the path of the current module with __FILE__

Expand your objects
Once you've learnt that the minimalistic (but incredibly powerful) support for OOP in Perl revolves above blessing hash references (yes, I know you can bless other objects, but it's pretty uncommon), you can draw similarities with JavaScript, and start to think of your Perl objects as objects that can be expanded at will with new fields and methods. Well, this is partially correct.

You'll have no problem in adding new data fields to your instances:
my $p1 = Person->New(); #where Person::New does not create any "color" property
$p1->{color} = "red";
but adding a method is a different story. This is cause the method look up mechanism in Perl is pretty different from JavaScript's one. Invoking a method in JavaScript will mean retrieving the corresponding function referenced by that object property (directly or through the prototype chain) and calling it with the corresponding "dynamic this". In Perl, when a method invokation is done on an object (a blessed reference), the interpreter will search that function in the package that was used to bless that object and will invoke it passing over to it the object as first argument.
So If you set an object property to a function reference, invoking it as if it were a normal method will fail (with an error like this: Can't locate object method "SayBye" via package "Person" , as that function is not in the Package itself, but you can use a sort of workaround:
#adding a method to an object
$p1->{SayBye} = sub{
	my $self = shift;
	return $self->{"name"} . " is saying Bye";
};

#the method look up does not work, as it's trying to find the method in the Person package, and it's not there
#Runtime error: Can't locate object method "SayBye" via package "Person" 
#print $p1->SayBye() . "\n";

#so we have to do it this way, by accessing the coderef in the object
print $p1->{SayBye}->($p1) . "\n";

I think we could do the above workaround much more elegant by means of AUTOLOAD, but I haven't had time yet to fiddle with it.

Monday, 10 February 2014

Objects are Not Dictionaries

First time I found out that ES6 was adding maps to JavaScript it seemed odd to me, as at that time I used to think about JavaScript objects as dictionaries/maps (you can add/delete/access items in them through string keys), but this is not true (or at least it's just partially true). I've been reminded of this fact while confirming that likewise Perl Hashes can only store strings as keys (they'll stringify any object that you use as a key).

So, first of all, JavaScript objects can only use strings as keys (compare this with .Net Dictionary<K,V> or Java's Map<K,V>, where K can be any type of object). This is the main issue addressed by ES6 Maps.

Second, as nicely explained here, a normal object already contains a number of "keys" inherited from Object.prototype, so that can pose a problem if the user of the object/dictionary attempts to use those keys as normal keys. There's a simple solution for that in ES5 (explained here), use for your dictionaries Objects with a null [[Prototype]], by means of Object.create(null);

By the way, posting a link to the ES5 and ES6 (draf) specifications adds some points to anyone's geek status :-D

Saturday, 1 February 2014

Perl is Cool 1: First Class Functions

Last months at work I've been doing Perl, Perl and more Perl, and honestly, it sounds pretty much better than you could think. I already gave my first impressions here. The language is full of idioms that I don't like at all, as on one side they are not particularly useful and on the other side they're so alien to any other language that make code pretty hard to understand. Nevertheless, it has most (and sometimes much more, ie, multiple inheritance and AUTOLOAD) of the features that you would expect in a modern, decent language. This is the first (and very basic) installment in (maybe) a series of entries about "The Good Parts" of Perl.

As already mentioned in that previous entry, JavaScript draws much influence from Perl, and Functions (yes, I know the Perl word for this is "subroutines", but I'll call them functions) is one of the clear areas were any JavaScripter will feel mainly at home. Perl sports First Class Functions (that is, you can create Higher Order Functions), meaning that you can pass functions around and create and return them.

We have Named functions

sub doBeep{
 my ($name) = @_;
 say "doBeep: " . $name;
}

We can pass these functions to other functions, the only thing to take into account is that you don't pass around functions, but references to functions (yeah, having to waste brain cycles in thinking whether something is "a something" or "a reference to that something" stinks to old, awful C++). So you'll have to do this:

#I have a reference to a function here
my $doBeepRef = \&doBeep;
testCallback($doBeepRef);

As we're passing a reference to a function, you'll have to dereference it to invoke it, which can be done in these 2 ways:

sub testCallback{
 my $callback = shift;
 print "testing callback\n";
 #so to invoke it I have to dereference it, either this way:
 $callback->("yup");
 #or this way:
 &{$callback}("yup");
}

We also have anonymous functions. When declared we already get a reference to a function. We can declare them in an assignment, as a parameter or as a return:

my $callback = sub{ 
 #whatever
};

testCallback(sub{
 #whatever
});

sub functionFactory{
 return sub{
  #whatever
 };
)

Anonymous functions are particularly useful cause Perl has Closures:

sub wrapString{
 my ($wrapper, $str) = @_;
 return $wrapper . $str . $wrapper;
}

sub wrapperFactory{
 my $wrapper = shift;
 return sub{
  return wrapString($wrapper, @_);
 }
}

my $underscoreWrapper = wrapperFactory('_');
print $underscoreWrapper->("hi") . "\n";

The normal use of closures in Perl is the same as in other languages, but I don't know how they are implemented internally (in JavaScript you have the [[scope]] thing, in C# and Groovy the compiler creates extra classes under the covers, so I'm not sure about how they behave in more complex scenarios. This document explains some oddities.

Update, 2014-02-07 I forgot to mention that Perl has the equivalent to JavaScript's Immediately invoked function expressions (IIFEs). Let's see an example creating a closure:

my $printWithCounter = sub{
	my $counter = 0;
	return sub{
		print "printing for time " . $counter++ . "\n";
	}
}->();

for my $i (1..5){
	$printWithCounter->();
}

Sunday, 19 January 2014

Byzantium

If you follow this blog you'll probably know that I'm pretty much into Vampire films, so since I knew that Byzantium was in production I've been quite interested on grabbing my hands on it. I've done so this weekend, and well, the film is pretty good.

The plot is quite original. While it touches on common Vampire topics like loneliness, it does it from a slightly different approach, more that the loneliness and pain of seeing everyone you can love age and die, this is the loneliness coming up from being constantly on the run escaping from someone else. This time, our main vampires are 2 beautiful women, a teenager and her young mother (hum, off the top of my head I can't think of any film were female vampires are portrayed as cute ladies) that are not part of the typical semi-aristocratic elite, but they lead a difficult life struggling to make ends meet.

The initial story behind how they turned into vampires develops as the current story does, so it keeps you intrigued until the end. The process that turns you into a vampire is quite new, not being bitten by another one, but traveling to a remote island to die and rebirth (this is quite a spectacular moment, with a water fall suddenly running red as the new immortal blood runs through your veins). Also, our vampires do not bite other humans to get their nutritious blood, but pinch their neck with a sort of extensible nail, and they are not killed with a stake or being burnt by daylight, but decapitated. The setting for the story is quite appropriate, some coastal cloudy town somewhere in the British islands, so it helps in creating the ambience of sorrow where the teen vampire dwells in (by the way, her sad expression reminds me in a way of Sibel Kekilli in When We Leave).

All in all, a quite enjoyable film you should give a try to.

Sunday, 12 January 2014

Lake, mural art from Berlin

I think there's no discussion that Berlin is the European capital of Street Art (and probably the world's too). Some of my favourite artists (El Bocho, Alias, C215...) live or have lived there, or at least have done some sort of pilgrimage there (Blu) to leave their mark.

In my last visit to Berlin, while glancing through the very interesting books in Big Brobot (if you happen to be in Berlin-Friedrichshain, don't miss it, it's a lovely shop), I came across the second installment about the work of another Berlin genius, Lake (Lake mural art from Berlin & other cities part 2). I have to sadly admit that I was unaware of this great artist, and only a few of the Berlin works shown in the book seem familiar to me (the ones in the East Side Gallery mainly, and I think some of the pieces that so much I've enjoyed in The Fifty Faces are his). His style is quite distinctive, particularly his "horizontal works", complex and appealing. Aesthetically impeccable, most of his creations contain some kind of (left) political message, either in the drawing itself, or steaming from the fact that it has been made in run-down impoverished areas, trying to create beauty there where ugliness is the day to day reality.

The weak point of this book is the lack of information about the location of the works (it just indicates the city), so I'll have to do quite a bit of research through the net to try to pinpoint the exact locations of his Berlin works so I can pay a visit in my next trip there.

This mural below is really powerful, and would deserve a better location (let's say Kreuzberg or Friedrhicshain), as it's real location (Schöneweide) has gained some notoriety in the last years for being the place of choice for many neo-nazi subhumans to settle down (there's even a pub/kneipe ran by one those pigs).

I feel sort of ashamed by such a short post, so I'll expand it by mentioning that you can visit the , the Street Art section in this blog by a "Berlin wanderer" to get a nice introduction to the Berlin scene, and that you should treat yourself visiting the beautiful work by this other Berlin genius, Alias (aesthetics + message, the way it should always be).

Saturday, 4 January 2014

Scala traits

I mentioned in a recent post how some .Net developers are embracing F# as a more modern language than C#. This prompted me to check some of its features and in the end this took me take a glimpse to a couple of F# vs Scalar discussion. As I I lack of a "functional programming mindset" many elements in those discussions are alien to me, but the thing is that Scala sports a really interesting feature, traits/mixins.

Well, Traits/Mixins seem like an eternal source of conflict: what's the difference, are they just the same? I wrote about it some time ago and I think the conclusion I had drawn at that time after reading several materials on the topic is still right. Anyway, in Scala they're 2 parts of the same thing, we define traits, and then adding a trait to a class or instance is called mixin class composition. There are excellent examples like this all over the net, so I won't repeat code here. The idea is that traits can have both methods and properties (data fields), and can be mixed in into new classes or new instances, enabling some taste of Multiple Inheritance.

If we compare this to what is offered by Java 8 and Default Interface Implementation we can see that Scala traits are much more powerful. The Java 8 counterpart only allows inheriting behaviour (methods), while Scala allows inheriting both behaviour and state (notice that given than Scala Traits can have state, they have constructors. Furthermore, we can mixin traits not just into a new class, but directly into a new instance (I guess the compiler will do some magic under the covers to create new classes for such instances).

One thing that to my knowledge is missing is the ability to add a trait to an already existing instance (so we can't expand existing objects as we do in JavaScript, Groovy (ExpandoMetaClass) or even C# (with dynamic)).

So Scala traits are a really powerful feature that I would very much welcome in C#, but I've read some statements that confuse me a bit. Some people talk about how you can use traits for AOP. At first instance this article seemed really interesting. You use a trait to override a method to which you want to add the crosscutting concern. But after a second thought, the thing is that this leads to tons of code repetition. For each method you want to override you'll have to add one method to the trait with the extra code and the call to super, and you'll have to do this for each class. So, maybe it's that I'm missing something, but otherwise this approach seems terribly weak when compared to the normal AOP techniques using Dynamic Proxies and interception.

A concept sometimes mentioned when talking about Mixins and Traits is Monkey Patching. I think the difference lies on the fact that while Mixins/Traits are used when creating new classes (or instances), Monkey Patching is applied to existing classes or instances. In Scala I think you have access to some sort of Monkey Patching by means of implicit.

Finally, I'd like to recommend this excellent series comparing features in 3 of the more valued alternative JVM languages: Groovy, Scala and Clojure. By the way, I absolutely agree with this phrase by Martin Fowler mentioned there:

The legacy of Java will be the platform, not the language.