Monday, 18 October 2010

Lazy Dynamic Proxy

Lazy<T> has been a nice addition to the .Net 4 framework, providing us with a standard way to do lazy initialization. It's one of those damn simple thinks that you wonder, why wouldn't I think about it before?.
In short, Lazy instances are proxies around instances of T that won't get created until they are used for first time, through the Lazy<T>.Value property.

So, instead of directly creating an instance of CostlyObject (costly either in terms of initialization time or memory consumption), we create an instance of Lazy<CostlyObject> and use the .Value property in order to access any method or property.


Lazy p1 = new Lazy(()=> new Person("xose", 34));
Console.WriteLine(p1.Value.SayHi());


You can see the full code here.

I pretty like it, but I see a problem with it, its usage is not transparent. The client code is fully aware of being working with a proxy object and needs to adapt to its semantics (use myLazy.Value.Whatever instead of myObject.Whatever). We can think this is OK, but well, we could think of "lazyness" as an implementation detail that we don't want to share with the client.
Even worse, this won't work for already existing code. There's not inheritance relationship between Lazy<T> and T, so we can't happily pass a Lazy<T> object to a piece of code expecting a T object...

All this I've said above immediately rings a bell for me, Dynamic Proxies and Interception. This time we don't want to intercept calls to log something, but to create the real object.
So, time again for Castle DynamicProxy.
My first intention was to use a Class Proxy. This does not make sense. I would be creating an instance of a class inheriting from the T class (ProxyGenerator.CreateClassProxy<T> creates that new class and returns an instance of that class). Given how constructors and inheritance work, any child class constructor need to call a Base class constructor (either in an explicit or implicit fashion) so I would be building the costly object since the first moment (unless I were using some trick of having a dumb Base constructor that is not costly, but in the end is not useful...) so that's not the way to go.

As we have a problem with class inheritance here, we'll have to use a different approach, Interface implementation.
As you can read in this excellent tutorial, we have 3 options when it comes to interface proxies. 2 of them have the same problem as the previous mechanism, thought the created proxy is implementing an interface, it inherits from the proxied class, so it's useless for this. But we have a third option, Proxy without target:

Proxy without target. This one is tricky. You don’t supply target implementation for the interface. Dynamic Proxy generates it for you at runtime, using interceptors to provide behavior for its methods.

So, we generate a proxy class that implements the interface, and use an interceptor to lazy create and reference the instance of the real class.
We have 2 classes then, one that generates the Proxy, and another one for the Interceptor


public class LazyGenerator
{
ProxyGenerator generator = new ProxyGenerator();

//T is an interface
public T GetLazy(Func constructor) where T:class
{
T proxy = generator.CreateInterfaceProxyWithoutTarget(new LazyInterceptor(constructor));
return proxy;
}
}

public class LazyInterceptor: IInterceptor where T:class
{
private T target;
private Func constructor;

public LazyInterceptor(Func constructor)
{
this.constructor = constructor;
}

public void Intercept(IInvocation invocation)
{
Console.WriteLine("intercepted");
this.target = this.target ?? this.constructor();

//now invoke the method in the real object
//this works fine both for methods and properties, as in the case of a property this invocation.Method would be the get_propertyName, set_propertyName
invocation.ReturnValue = invocation.Method.Invoke(this.target, invocation.Arguments);
}
}

The constructor delegate passed to the Interceptor contains the invocation to constructor of the proxied class (it's just the same approach used by Lazy<T>.
You've got a full sample here where I lazy create a Repository. (zip with the needed Castle Assembly here).

As you can see in the comments it's interesting how this line in the interceptor:

invocation.Method.Invoke(this.target, invocation.Arguments);

works both for intercepted method calls and properties.
This is pure logic, a C# property "X" gets translated by the C# compiler into a "get_X" and a "set_X" method, so that's what we have in the invocation.Method when we access a property through the proxy.

If you happen to read this blog regularly (which I doubt :-)) you'll probably have realized that this entry is rather related to this previous one.

Thursday, 14 October 2010

jQuery Object

Quite often when I get back to jQuery after some time without touching it, I get some confusion with the almighty jQuery object (well, I would say this is sample of the God Object antipattern).
When we use some of the selection methods to obtain DOM elements, we get an instance of the jQuery object containing the selected DOM elements (DOM elements, not jQuery wrappers, so we usually have to wrap them into a jQuery object again with $(this) for additional processing). This instance is similar to an Array, but it's not, it's an Array-like object.
It has a length property and the DOM elements are accessible through numeric indexes, so how is this?
Each DOM element to be contained by the instance of the jQuery object is added to this instance through an increasing numeric property, and a length property is also added and kept updated. Bear in mind that for these numeric properties we can only use the "[]" notation, not the "." notation. Yes, all this is one of those magical JavaScript things. What this means is that we can do this with an object:


var obj1 = {};

obj1.name = "xana";

obj1["age"] = 30;

obj1["0"] = "item1";

obj1.length = 1;

obj1[1] = "item2";
obj1.length = 2;


so we get an Array-like object, with a length of 2, 2 items accessible via numeric index and other 2 properties ("xana" and 30).
As it's not a real Array, there's some gotcha to take into account, for example, we should not iterate it with a for in loop if what we want is iterating its items collection. I mean, we can iterate (thought it's not much common) a true Array like this:

for (index in ar)
printf(ar[index]);


but used on our Array-like object, we would get a listing of all it's other properties and methods along with the indexed values.

Of course, the usual way to iterate our jQuery object is either with the .each jQuery instace method (not to be confused with the .each "static method")

var $aux = $("<ul><li>xose</li><li>xuan</li></ul>");
//jQuery object with an only item (ul)
var $peopleList = $aux.children("li");
//jQuery object with two items (li)
$peopleList.each(function()
{
printf($(this).text());
});


or with a normal for loop:

for(var i=0; i<$peopleList.length; i++)
printf($peopleList[i].innerHTML);


you can view/test the code here

Tuesday, 12 October 2010

Assayas

Yesterday I watched Boarding Gate, and impressive film by French director Olivier Assayas. It has common elements and a very similar feeling to the other film from this director that I had watched before, Demonlover (well, Demonlover is even better for me, but anyway both films are excellent).

The plot in both films deals with the dark side of the business world. Spying and fighting between two companies trying to gain control of the distribution of Anime porn in the West (Demonlover) and the troubles of a business investor going downhill and involved in a harsh sort of relationship with a femme fatale (Boarding Gate). Both films succed on adding interest and complexity to the story by setting up part of it in societies that still keep a high dose of mystery and charm for many of us, Japan and China.

The combination of action, eroticism and violence will keep you hooked until the end of both stories, and well, when I say eroticism this takes me to the other great common denominator of both films, they are starred by some absolutely gorgeous, ultra sexy women: the viking goddess Connie Nielsen and Gina Gerson in one case and Asia Argento and an Asian beauty in the other case.

Time to get my hands on any of the other Assayas' films, but these two have set the bar quite high.


Thursday, 7 October 2010

Nested ordered list

To my surprise I found out the other day that there does not seem to be a html+CSS way to create a nested ordered list. I mean, the typical index, something like this:
1. Europe
1.1 Germany
1.1.1 Hesse
1.1.2 Bavaria
1.2 UK
2. Asia

Using the normal html structure you would get something like this:

1 Europe
1 Germany
1 Hesse
2 Bavaria
2 UK
2 Asia

so, you have to resort to JavaScript to get the right numbering. It's pretty simple, and much more if you're using jQuery's magic, but anyway I think it can be helpful (at least as my personal repository), so here it is:

(you also need a change to your html, instead of <ol> elements you'll have to use <ul>, as it's javascript who's going to take care of all the numbering)



function orderNestedList($ulItem, curValue)
{
$ulItem.children("li")
.each(function(index)
{
var newValue = curValue + (++index) + ".";
$(this).prepend(newValue);
var children = $(this).children("ul");
if (children.length > 0)
orderNestedList($(children[0]), newValue);
});
}


you can see it at work here

Saturday, 2 October 2010

The Third Jihad

I've just watched this great North American documentary and I can only praise it and recommend it. It's one more wake up call to Westerns to stand up to radical Islam, to reverse the process of Islamization of our societies.

It's pretty good at pointing out the main enemies, risks, and weaknesses:

  • As I already commented in a previous post, Wahhabism, Saudi Arabia and the use of their petrodolars to indoctrinate moderate muslims in Western countries.

  • The absolute incapacity of Western society to understand the problem, prefering to live in a state of self delusion.

  • The faint hearted attitude of many Westerns (normal people and governments) that do not have the courage to say NO to the stupid requirements of some of the "new neighbours". Sure our culture has to change in many aspects, but it's evolution what it needs, not involving based on the "advice" of a medieval society

  • Treacherous politicians that put their private businesses before the public ones (that is, the people who elected them). As their private businesses are in hands of the Saudi theocracy... we know what happens...


It also reveals some facts that were unknown to me:

  • The cultural jihad is far more dangerous than the violent Jihad.

  • Non muslims are not allowed to set foot on Mecca

  • Saudis have given good amounts of money to Western universities to fund studies on "Arabic culture", "mutual understanding"... sounds good, but it's just pure and dirty proselytism...

  • Many muslims in USA that claim to be moderate when in public, are not that moderate at all


I quite like that from the first moment it tries to make it clear that the problem is not Islam, but radical Islam, and it's nice to see a (very)moderate muslim narrating the documentary. But I'd like to add something with regards to this, as I think moderates could be not that harmless sometimes:
I have no problem with moderate religious people, whether they are Christians, Jews, Muslims... when these people live with other moderate or very moderate people. Problem is that when moderate people live with extremist people, the former can get infected, and much more when the extremists have money and power...

There are moments in the documentary that are absolutely revolting, like the demonstrations of radical muslims asking for punishmen for homosexuals, their intentions to apply Sharia in Europe, their absolute convintion of bearing a superior moral order...
but sure the worst moments are when some of the contributors assert that the battle against extremist Islam in Euope is already lost, and it's terrible to hear that because probably they're sadly right, just think that in some European countries muslims will surpass non muslims in less than 50 years...

I have to admit that there are a few things I don't agree with:

One of them is the title itself. The producers claim that there have been 2 other big Jihads previous to the current one, the first in the 8th century, when they conquered southern Italy and most of the Iberian Peninsula (but not my homeland, Asturies:-)), and the second in the 16th and 17ht centuries, when the Ottoman Empire conquered good part of Eastern Europe but hopefully was defeated twice at the doors of Vienna.
From my perspective none of these previous invasions can be considered as dangerous as the current one, the Islamic invaders at those two occasions were not at all as harmful as they are now, they brought a culture that was partially compatible with the European culture of the time, nothing to do with the Wahhabi medieval barbarism with which they try to replace Western 21st century civilization.

Another point I disagree with is their vision on Iran. I don't think Iran is such a threat, on the contrary I hope some day the Iranian people (much more moderate than many Westerns think) will manage to overthrow the theocratic government that they've been suffering for decades and become again the great society they once were.

Anyway this film is an absolute must, and if I've not managed to convince you yet, maybe this statement that opens the film will do.

"This is not a film about Islam. It is about the threat of Radical Islam. Only a small percentage of the world's 1.3 billion Muslims are radical. This film is about them."


Wednesday, 22 September 2010

Multicore Bottleneck

Today, while reading some materials about Parallel Programming, partitioning datasets and so on, some old echos from the past came to my mind.

In most of the simple samples that I've seen lately, a bunch of data gets loaded into memory, and then the memory dataset is partitioned and each thread reads data from one of the data partitions. We do the whole loading into memory before launching the threads because otherwise different threads would be accessing to disk simultaneously and the I/O bottleneck would keep threads stuck while the I/O operation for other thread gets completed.

OK, I've said bottleneck. There's one that's been well known since long ago, Memory bottleneck. Years ago, as CPUs got faster and faster, the memory access technology was unable to keep up, and we had the problem of a fast CPU on hold waiting for the data retrieval from memory... We have caches and branch prediction to soften the problem, but anyway, it's still there.

Since some years ago CPUs speed has barely increased, but we have several cores, and more and more cores to come... This means, that it's not only that an operation will be we waiting for the memory to provide the data it needs, it's that multiple parallel operations will be waiting for the same memory to provide those data through the same data bus that we had years ago.
This sounds messy, so I thought sure there was some work around in place for this that I was missing (it's been a long while since the times when I was a hardware freak following the last improvements in chipsets and buses...), but after some googling it doesn't seem so, and in fact we can say that Multicore makes the memory bottleneck worse.

Saturday, 18 September 2010

CCTV

I was in London last week, and once again (despite having been there many times) the omnipresence of CCTV cameras in public spaces continues to astonish me.
I have mixed feelings about them, but in general, however strange this may seem to many of my friends, in this particular case positive feelings win.

I think central London (taking as central a really large area) is one of the safest places that one can find in a modern metropolis. I don't like being surveilled by the the police, the state or whoever... but if I weigh up the moral disturbance that being observed causes me against the risk of being mugged by a violent gang, finding all public toilets, phones... vandalized, etc... I'm afraid I've turned so conservative to happily accept being monitored...
Well, maybe this thought is common to many Londoners, as otherwise it would be hard to understand that a population that has so fiercely opposed to Identity Cards could accept the attack to privacity that CCTV involves.

Related to this (but with a much broader scope) Tate Modern is hosting an exhibition that seems pretty interesting:

Exposed: Vouyerism, surveillance and the camera

No doubt CCTV has been, is, and will ever be a hot, controversial topic, and street art clearly reflects it:

Banksy, Marble Arch, London, 2004:




Marble Arch, London, September 2010:




Frankfurt, August 2010:


Update 2011/06/02
When I was in Munich last April (world famous for its impressive Bavarian baroque architecture, but its less known Art Nouveau treasures are also stunning) I came across this good addition to this post:



I think it reads something like: "Dictatorship of Safety"