viernes, 27 de mayo de 2011

erlang o c++ mejorado


 C++ to Erlang, massive savings

Written on 21 October 2009

I've heard many anecdotes and claims about how many lines of code are saved when you write in Erlang instead of [C++/other language]. I'm happy to report that I now have first-hand experience and some data to share.
I initially wrote Playdar in C++ (using Boost and Asio libraries), starting back in February this year. I was fortunate to be working with some experienced developers who helped me come to terms with C++. There were three of us hacking on it regularly up until a few months ago, and despite being relatively new to C++, I'll say that we ended up with a well designed and robust codebase, all things considered.

alternativas a livego

livego  es  una  aplicacion web  que   conjunta  muchas  redes  sociales,  pero noe s la unica  opcion, he  aqui  otras  muy buenas  opciones


http://alternativeto.net/software/livego/

jueves, 26 de mayo de 2011

qi4ji for .net Commpositio Oriented Programing

 obtenido de  aqui

A new programming paradigm has been born in distant land of Java. Qi4j introduces the first Composite Oriented Programming (COP) concept to the world, and has drawn massive interest among Java crowd ever since.
It drove me to start a work on implementing Composite Orientation on .Net as a project named Composheep. This will be an open-source lightweight COP framework (as defined by Qi4j) that I will build incrementally as I write each step on this blog as “Roll Your Own COP” series. I publish the project in CodePlex as LGPL.
Let’s start from the mission of COP. One of the biggest flaws of OOP is that it’s not object oriented at all. If anything, OOP is Class-Oriented, since class is the primary citizen that all objects are derived from. Not the other way round.
As an example, I am a programmer at work, a driver in a car, a researcher in kitchen, and a hunter and a pray in the jungle. As an object, my role (class) constantly changes depending on contexts. Some objects also traverses different scope boundaries. For instance, a Person will have its classes changing over time. New abilities are learnt, from Kid, Student, Dancer, Ninja, and he will eventually due, but it doesn’t mean that the Person object should be deleted from the system since the “memory” of him may live for long time. In a conventional OOP system, we will need to transfer some of the states across instances of different classes. In Composite Oriented Programming, they are all ONE instance. We assign role (Class) to an object. Not instantiating objects based on a destined class. Object is therefore the primary citizen of COP. Please visit Qi4j site for more detail.
One of the most important COP concepts is mixin, in which multiple reusable classes are mixed to form a solid composite. It relies much on Java class generation technique, in which .net is always known far inferior. But, as the first part of the series, I will show how easy it actually is to build our own Mixins implementation on .net using Castle DynamicProxy, in only 15 minutes.
Our objective is to achieve a robust Mixins builder that is smart enough to:
- Handle both properties and methods
- Differentiate parameters overload. E.g. foo() and foo(string)
- Handle generic methods. E.g. foo<T>()
- Differentiate generics overload. E.g. foo<T>() and foo<T,Y>()
- Declarative programming using attributes
As a sample use-case, first I will define a composite of Person that is composed from 2 mixins: HasName and CanFight. I want to define the composite in the following fashion:
1[Mixin(typeof(HasNameImpl), typeof(Fighter))]
2public interface Person: HasName, CanFight
3{
4}
Note that Person, as a composite, is defined as an interface. We won’t write any implementation of Person since it will be automatically derived by composing 2 mixin implementations together. We declaratively specify that we wish to use HasNameImpl and Fighter as mixin implementor by using Mixin attribute.
Here is the definition of the mixins:
01public interface HasName
02{
03    string FirstName{ get; set;}
04    string LastName { get; set;}
05 
06    string IntroduceSelf();
07    string IntroduceSelf(string target);
08}
09 
10public interface CanFight
11{
12    string Kick<Target>();
13    string Kick<LTarget, RTarget>();
14}
And the following is the implementation of each mixins:
01public class HasNameImpl: HasName
02{
03    public string FirstName {get; set;}
04    public string LastName {get; set;}
05 
06    public string IntroduceSelf()
07    {
08        return Console.Writeln(
09            "Hi there, I am {0} {1}",
10            FirstName, LastName);
11    }
12 
13    public string IntroduceSelf(string target)
14    {
15        return Console.Writeln(
16            "Hi {0}, I am {1} {2}",
17            target, FirstName, LastName);
18    }
19}
01public class Fighter: CanFight
02{
03    public string Kick<Target>()
04    {
05        return Console.Writeln
06            ("Roundhouse kick to {0}",
07        typeof (Target).Name);
08    }
09 
10    public string Kick<LTarget, RTarget>()
11    {
12        return Console.Writeln
13            ("Left foot to {0}, and right foot to {1}",
14        typeof (LTarget).Name,
15        typeof (RTarget).Name);
16    }
17}
The following is how I want the client code to be:
1CompositeBuilder builder = new CompositeBuilder();
2Person person = builder.BuildComposite<Person>();
3 
4person.FirstName = "Hendry";
5person.LastName = "Luk";
6person.IntroduceSelf());
7person.IntroduceSelf("Goofy"));
8person.Kick<Dog>());
9person.Kick<Dog, DebtCollector>());
We instantiate an object of Person, whose implementation is generated dynamically by mixing HasNameImpl and Fighter together to form a complete Person. This way, we will be able to separate a class into smaller chunks of fragment (mixin) that can be reused effectively.
I think this use simple use-case provides a good coverage to all our 5 requirements. It exploits the use of properties, methods with overloaded parameters, and methods with overloaded generics.
Now, to make this work, we will need to write the CompositeBuilder as part of our Composheep solution. We will be using Castle DynamicProxy, which is a lightweight proxy generator used in many open-source frameworks like nHibernate, Windsor, Aspect#, etc.
Here is the implementation of CompositeBuilder. It searches for MixinAttributes in supplied type, then grab the mixin implementer types that was provided as attribute parameter.
01public class CompositeBuilder
02{
03    private ProxyGenerator generator = new ProxyGenerator();
04 
05    public T BuildComposite<T>() where T : class
06    {
07        CompositeInterceptor interceptor = new CompositeInterceptor();
08 
09        object[] attributes =
10        typeof(T).GetCustomAttributes(typeof(MixinAttribute), true);
11        foreach (MixinAttribute mixin in attributes)
12        {
13            foreach (Type mixinType in mixin.Types)
14                interceptor.AddMixin(Activator.CreateInstance(mixinType));
15        }
16 
17        return generator.CreateInterfaceProxyWithoutTarget(interceptor);
18    }
19}
ProxyGenerator is an API from Castle DynamicProxy that we use to dynamically define implementation of composite interface. The most important part of this only method is that in each mixin type defined in mixin attribute, we use default constructor to instantiate the mixin, and pass it to CompositeInterceptor. It’s a custom proxy interceptor that we will create to handle each composite method invocation to its corresponding mixin implementation.
Here is the code for CompositeInterceptor.
01internal class CompositeInterceptor : IInterceptor
02{
03    Dictionary methodTargetMap =
04        new Dictionary();
05 
06    public void AddMixin(object mixin)
07    {
08        Type targetType = mixin.GetType();
09 
10        MethodInfo[] methods =
11        targetType.GetMethods(
12        BindingFlags.Instance |
13        BindingFlags.Public |
14        BindingFlags.NonPublic);
15 
16        foreach(MethodInfo method in methods)
17        {
18            // Skip members declared in System.Object
19            if (method.DeclaringType == typeof(object))
20                continue;
21 
22            methodTargetMap.Add(method.ToString(), mixin);
23        }
24    }
25 
26    // Implementing IInterceptor.Intercept method
27    public void Intercept(IInvocation invocation)
28    {
29        object target = FindMixin(invocation.Method);
30        if (target == null)
31            throw (new NotImplementedException());
32 
33        invocation.ReturnValue =
34        invocation.Method.Invoke(
35        target, invocation.Arguments);
36    }
37 
38    private object FindMixin(MethodInfo callMethod)
39    {
40        if (callMethod.IsGenericMethod)
41            callMethod = callMethod.GetGenericMethodDefinition();
42 
43        foreach (String method in methodTargetMap.Keys)
44        {
45            if (method == callMethod.ToString())
46 
47                return methodTargetMap[method];
48        }
49        return null;
50    }
51}
The idea is that AddMixin method will map each method signature with a mixin instance in a Dictionary. Therefore, when we intercept a proxy method invocation, we will be able to lookup the dictionary for the method signature, and get the mixin instance. Finally, the invocation will be redirected to that mixin instance.
The easiest way to lookup matching method signature (in FindMixin method) is by using MethodInfo.ToString() since it gives us the method name, parameters types, return type, and generic parameters. So we will be using this as the key of the Dictionary as well.
The only problem with generic parameter is that we will be storing open-generic method signature, for example, string Kick() in AddMethod method during interface introspection. But during invocation, we will get passed with a closed-generic method, for instance, string Kick(). To get around this, we put 2 lines on top of FindMixin:
1if (callMethod.IsGenericMethod)
2callMethod = callMethod.GetGenericMethodDefinition();
It converts void Kick() back into void Kick(). And this is all we need to build our mixin builder! Run the application, and this is what we got:

Just few minutes of pretty straightforward code and we’ve got the building block for our Composheep in place. You can download the code for this episode here. Coming next, in the second episode, we will be building the second features of COP: concerns and side-effects.

miércoles, 25 de mayo de 2011

6NF : sexta forma normal


In a nutshell, 6NF means that every relation consists of a candidate key plus no more than one other (non-key) attribute. To take up your example, if an "item" is identified by a ProductCode and the other attributes are Description and Price then a 6NF schema would consist of two relations (* denotes the key in each):
ItemDesc {ProductCode*, Description}
ItemPrice {ProductCode*, Price}
This is potentially a very flexible approach because it minimises the dependencies. That's also its main disadvantage however, especially in a SQL database. SQL makes it hard or impossible to enforce many multi-table constraints. Using the above schema, in most cases it will not be possible to enforce a business rule that every product must always have a description AND a price. Similarly, you may not be able to enforce some compound keys that ought to apply (because their attributes could be split over multiple tables).
So in considering 6NF you have to weigh up which dependencies and integrity rules are important to you. In many cases you may find it more practical and useful to stick to 5NF and normalize no further than that.



I actually started putting an answer together, but I ran into complications, because you (quite understandably) want a simple example. The problem is manifold.
First I don't have a good idea of your level of actual expertise re Relational Databases and 5NF; i don't have a starting point to take up and then discuss the specifics of 6NF,
Second, just like any of the other NFs, it is variegated. You can just barely step into it; you can implement 6NF for certan tables; you can go the full hog on every table, etc. Sure there is an explosion of tables, but then you Normalise that, and kill the explosion; that's an advanced or mature implementation of 6NF. No use providing the full or partial levels of 6NF, when you are asking for the simplest, most straight-forward example.
I trust you understand that some tables can be "in 5NF" while other are "in 6NF".
So I put one together for you. But even that needs explanation.
Now SQL barely supports 5NF, it does not support 6NF at all (I think dportas says the same thing in different words). Now I implement 6NF at a deep level, for performance reasons, simplified pivoting (entirely table not the silly PIVOT function in MS), columnar access, etc. For that you need a full catalogue, which is an extension to the SQL catalogue, to support the 6NF that SQL does not support, and maintain data Integrity and business Rules. So you really do not want to implement 6NF for fun, you only do that if you have a need, because you have to implement a catalogue. (This is wht the EAV crowd do not do, and this is why most EAV systems have data integrity problems.)
But most people who implement 6NF don't implement the deeper level, with a full catalogue. They have simpler needs, and thus implement a shallower level of 6NF. So let's take that, to provide a simple example for you. Let's start with an ordinary Product table that is declared to be in 5NF (and let's not argue about what 5NF is). The company sells various different kinds of Products, half the columns are mandatory, and the other half are optional, meaning that depending on the Product Type, certain columns may be Null. While they may have done a good job with the database, the Nulls are now a big problem: columns that should be Not Null for certain ProductTypes are Null, because the declaration states NULL, and their app code is only as good as the next guys.
So they decide to go with 6NF it fix that problem, because the subtitle of 6NF states that it eliminates The Null Problem. Sixth Normal Form is the irreducible Normal Form, there will be no further NFs after this, because the data cannot be Normalised further. The rows have been Normalised to the utmost degree. The definition of 6NF is:
a table is in 6NF when the row contains the Primary Key, and at most one, attribute.
Notice that by that definition, millions of tables across the planet are already in 6NF, without having had that intent. Eg. typical Reference or Look-up tables, with just a PK and Description.
Right. Well our friends look at their Product table, which has eight non-key attributes, so if the make the Product table 6NF, they will have eight sub-Product tables. Then there is the issue that some columns are Foreign Keys to other tables, and that leads to more complications. And they note the fact that SQL does not support what they are doing, and they have to build a smal catalogue. Eight tables are correct, but not sensible. Their purpose was to get rid of Nulls, not to write a little subsytem around each table.
Simple 6NF Example
Readers who are unfamiliar with the Standard for Modelling Relational Databases may find IDEF1X Notation useful in order to interpret the symbols in the example.
So typically, the Product Table retains all the Mandatory columns, especially the FKs, and each Optional column, each Nullable column, is placed in a separate sub-Product table. That is the simplest form I have seen. Five tables instead of eight. In the Model, the four sub-Product tables are "in 6NF"; the main Product table is "in 5NF".
Now we really do not need every code segment that SELECTs from Product to have to figure out what columns it should construct, based on the ProductType, etc, so we supply a View, which is essentially provides the 5NF "view" of the Product table cluster.
The next thing we need is the basic rudiments of an extension to the SQL catalog, so that we can ensure that the rules (data integrity) for the various ProductTypes are maintained in one place, in the database, and not dependent on app code. The simplest catalogue you can get away with. That is driven off ProductType, so ProductType now forms part of that Metadata. You can implement that simple structure without a catalogue, but I would not recommend it.
Finally, yes, there are at least four further levels of Normalisation (Normalisation is a Principle, not a mere reference to a Normal Form), that can be applied to that simple 6NF Product cluster, providing more control, less tables, etc. The deeper we go, the more extensive the catalogue. When you are ready, just ask, I have already erected the models and posted details in other answers.

martes, 24 de mayo de 2011

Composite Oriented Programming con qi4ji en .net

obtenido de  aqui

An entry about arcitechture | design patterns Publication date 27. February 2008 18:18
I've written a series of post on AOP lately (here, here and here), and in the last part I promised to tackle mixins and introductions in a future post. When I was doing my research for just that, I came cross a Java framework (just humor me :p) called Qi4j (that's 'chee for jay'), written by Swedish Richard Öberg, pioneering the idea of Composite Oriented Programming, which instantly put a spell on me. Essentially, it takes the concepts from Aspect Oriented Programming to the extreme, and for the past week I’ve dug into it with a passion. This post is the first fruits of my labor.

OOP is Not Object Oriented!

One of the things that Richard Öberg argues, is that OOP is not really object oriented at all, but rather class oriented. As the Qi4j website proclaims, "class is the first class citizen that objects are derived from. Not objects being the first-class citizen to which one or many classes are assigned". Composite oriented programming (COP) then, tries to work around this limitation by building on a set of core principles; that behavior depends on context, that decoupling is a virtue, and that business rules matter more. For a short and abstract explanation of COP, see this page. In the rest of this post I'll try and explain some of its easily graspable benefits through a set of code examples, and then in a future post we'll look at how I've morphed the AOP framework I started developing in the previous posts in this series into a lightweight COP framework that can actually make it compile and run.

Lead by Example

Lets pause for a short aside: obviously the examples presented here are going to be architectured beyond any rational sense, but the interesting part lies in seeing the bigger picture; imagine the principles presented here applied on a much larger scale and I'm sure you can see the benefits quite clearly when we reach the end.
Imagine that we have a class Division, which knows how to divide one number by another:
public class Division
{
    public Int64 Dividend { get; set; }
 
    private long _divisor = 1;
 
    public Int64 Divisor
    {
        get { return _divisor; }
        set 
        {
            if(value == 0)
            {
                throw new ArgumentException("Cannot set the divisor to 0; division by 0 is not allowed.");
            }
 
            _divisor = value; 
        }
    }
 
    public Int64 Calculate()
    {
        Trace.WriteLine("Calculating the division of " + this.Dividend + " by " + this.Divisor);
 
        Int64 result = this.Dividend/this.Divisor;
 
        Trace.WriteLine("Returning result: " + result);
 
        return result;
    }
}
Consider the code presented above. Do you like it? If you've followed the discussion on AOP in the previous posts, then you should immediately be able to identify that there are several aspects tangled together in the above class. We've got data storage (the Dividend and Divisor properties), data validation (the argument check on the Divisor setter), business logic (the actual calculation in the Calculate method) and diagnostics (the Trace calls), all intertwined. To what extent is this class reusable if I wanted to implement addition, subtraction or multiplication calculations? Not very, at least not unless we refactored it. We could make the Calculate method and the properties virtual, and thus use inheritance to modify the logic of the calculation - and since this is a tiny example, it would probably look OK. But again, think bigger - how would this apply to a huge API? It would easily become quite difficult to manage as things got more and more complex.

Design by Composition

With a COP framework, we can implement each aspect as a separate object and then treat them as mixins which blend together into a meaningful composite. Sounds confusing? Lets refactor the above example using an as of yet imaginary COP framework for .NET (which I’m currently developing and will post the source code for in a follow-up post), and it'll all make sense (hopefully!).
Above, we identified the four different aspects in the Division class - so let's implement each of them. First, we have the data storage:
public interface ICalculationDataAspect // aspect contract
{
    long Number1 { get; set; }
    long Number2 { get; set; }
}
 
public class CalculationDataAspect : ICalculationDataAspect // aspect implementation
{
    public long Number1 { get; set; }
    public long Number2 { get; set; }
}
In this example, the data storage is super easy – we just provide a set of properties (using the C# 3.0 automatic properties notation) that can hold the values in-memory. The second aspect we found, was the business logic – the actual calculation:
public interface ICalculationLogicAspect
{
    long Calculate();
}
 
public class DivisionLogicAspect : ICalculationLogicAspect
{
    [AspectRef] ICalculationDataAspect _data;
 
    public long Calculate()
    {
        return _data.Number1 / _data.Number2;
    }
}
Here we follow the same structure again, by defining the aspect as an interface and providing an implementation of it. In order to perform the calculation however, we need access to the data storage aspect so that we can read out the numbers we should perform the calculation on. Using attributes, we can tell the COP framework that we require this reference, and it will provide it for us at runtime using some dependency injection trickery behind the scenes. It is important to notice that we’ve now placed a constraint on any possible composition of these aspects – the DivisionLogicAspect now requires an ICalculationDataAspect to be present in any composition it is part of (our COP framework will be able to validate such constraints, and tell us up front should we break any). It is still loosely coupled however, because we only hold a constraint on the contract of that aspect, not any specific implementation of it. We'll see the benefit of that distinction later.
The third aspect we have, is validation. We want to ensure that the divisor is never set to 0, because trying to divide by zero is not a pleasant experience. Validation is a type of advice, which was introduced at length earlier in my AOP series. We've seen it implemented using the IAdvice interface of my AOP framework, allowing us to dynamically hook up to a method invocation. However, the advice we’re implementing here is specific to the data aspect, so with our COP framework we can define it as concern for that particular aspect, which gives us a much nicer implementation than an AOP framework could - in particular because of its type safety. Just look at this:
public abstract class DivisionValidationConcern : ICalculationDataAspect
{
    [ConcernFor] protected ICalculationDataAspect _proceed;
 
    public abstract long Number1 { get; set; }
 
    public long Number2
    {
        get { return _proceed.Number2; }
        set
        {
            if (value == 0)
            {
                throw new ArgumentException("Cannot set the Divisor to 0 - division by zero not allowed.");
            }
 
            _proceed.Number2 = value; // here, we tell the framework to proceed with the call to the *real* Number2 property
        }
    }
}
I just love that, it's so friggin' elegant ;). Remember that an advice is allowed to control the actual method invocation by telling the target when to proceed – we’re doing the exact same thing above, only instead of dealing with a generic method invocation we're actually using the interface of the aspect we're advising to control the specific invocation directly. In our validation, we validate the value passed into the Divisor setter, and if we find it valid then we tell the target (represented by a field annotated with an attribute which tells the COP framework to inject the reference into it for us, much like we did with aspects earlier) to proceed with the invocation; otherwise we throw an exception. This particular concern is abstract, because we only wanted to advise a subset of the methods in the interface. That's merely a convenience offered us by the framework - under the covers it will automatically complete our implementation of the members we left abstract.
Only one aspect remains now, and that is the logging:
public class LoggingAdvice : IAdvice
{
    public object Execute(AdviceTarget target)
    {
        Trace.WriteLine("Invoking method " + target.TargetInfo.Name + " on " + target.TargetInfo.DeclaringType.FullName);
 
        object retValue;
 
        try
        {
            retValue = target.Proceed();
        }
        catch(Exception ex)
        {
            Trace.WriteLine("Method threw exception: " + ex.Message);
            throw;
        }
 
        Trace.WriteLine("Method returned " + retValue);
 
        return retValue;
    }
}
We’ve implement it as a regular advice, like we've seen earlier in AOP, because it lends itself to much wider reuse than the validation concern did.
Having defined all our aspects separately, it is now time to put them back together again into something that can actually do something. We call this the composite, and it is defined as follows:
[Mixin(typeof(ICalculationDataAspect), typeof(CalculationDataAspect))]       
[Mixin(typeof(ICalculationLogicAspect), typeof(DivisionLogicAspect))]
[Concern(typeof(DivisionValidationConcern))]
[Concern(typeof(LoggingAdvice))]
public interface IDivision : ICalculationDataAspect, ICalculationLogicAspect 
{ }
Basically, we’ve just defined the implementation of an interface IDivision as a composition of the data and logic aspects, and sprinkled it with the two concerns (the validation concern and the logging advice). We can now use it to perform divisions:
IDivision division = Composer.Compose<IDivision>().Instantiate();
division.Number1 = 10;
division.Number2 = 2;
 
Int64 sum = division.Calculate();
That’s pretty cool, no? Take a moment to just think about what doors this opens. To what extent do you think our code is reusable now, if we wanted to implement addition, subtraction and so forth? That’s right – all we’d need to do is substitute the implementation of the calculation aspect with one that performs the required calculation instead of division, and we're done. Let’s do subtraction, for example:
public class SubtractionLogicAspect : ICalculationLogicAspect
{
    [AspectRef] ICalculationDataAspect _data;
 
    public long Calculate()
    {
        return _data.Number1 - _data.Number2;
    }
}
That’s it! The rest we can reuse as is, building a new composite:
[Mixin(typeof(ICalculationDataAspect), typeof(CalculationDataAspect))]
[Mixin(typeof(ICalculationLogicAspect), typeof(SubtractionLogicAspect))]
[Pointcut(typeof(LoggingAdvice))]
public interface ISubtraction : ICalculationDataAspect, ICalculationLogicAspect
{ }
Notice that we just left out the validation concern in this composite, as it is no longer needed. What if we wanted our subtraction to only ever return positive numbers? Easy! We’ll just implement an absolute number concern:
public class AbsoluteNumberConcern : ICalculationLogicAspect
{
    [ConcernFor] protected ICalculationLogicAspect _proceed;
 
    public long Calculate()
    {
        long result = _proceed.Calculate();
 
        return Math.Abs(result);
    }
}
And then update the composition to include it:
[Mixin(typeof(ICalculationDataAspect), typeof(CalculationDataAspect))]
[Mixin(typeof(ICalculationLogicAspect), typeof(SubtractionLogicAspect))]
[Concern(typeof(AbsoluteNumberConcern))]
[Pointcut(typeof(LoggingAdvice))]
public interface ISubtraction : ICalculationDataAspect, ICalculationLogicAspect
{ }

To Be Continued…

I hope this post has whet your appetite for more on this subject, as I will certainly pursue it further in future posts. I’ve already implemented a prototype framework that supports the above examples, which builds on my previously posted AOP framework, and I’ll post the source code for that soon. If you want to dig deeper right now (and don’t mind a bit of Java), then I suggest you head over to the Qi4j website and poke about there. Richard Öbergs blog also provides great insight.

Patrón Inversión de Control (IoC)

obtenido de aqui

Patrón Inversión de Control (IoC)

La Inversión de Control es un patrón de diseño pensado para permitir un menor acoplamiento entre componentes de una aplicación y fomentar así el reuso de los mismos.

Un problema, una solución

Como todo patrón, comienza planteando un problema y el viene a resolver.
Muchas veces, un componente tiene dependencias de servicios o componentes cuyos tipos concretos son especificados en tiempo de diseño.
ioc1
En el ejemplo de la imagen, clase A depende de ServiceA y de ServiceB.
Los problemas que esto plantea son:
  • Al reemplazar o actualizar las dependencias, se necesita cambiar el código fuente de la clase A.
  • Las implementaciones concretas de las dependencias tienen que estar disponibles en tiempo de compilación.
  • Las clases son difíciles de testear aisladamente porque tienen directas definiciones a sus dependencias. Esto significa que las dependencias no pueden ser reemplazadas por componentes stubs o mocks.
  • Las clases tienen código repetido para crear, localizar y gestionar sus dependencias.
Aquí la solución pasa por delegar la función de seleccionar una implementación concreta de las dependencias a un componente externo.
El control de cómo un objeto A obtiene la referencia de un objeto B es invertido. El objeto A no es responsable de obtener una referencia al objeto B sino que es el Componente Externo el responsable de esto. Esta es la base del patrón IoC.
El patrón IOC aplica un principio de diseño denominado principio de Hollywood (No nos llames, nosotros te llamaremos).

Usos

El patrón IoC se puede utilizar cuando:
  • Se desee desacoplar las clases de sus dependencias de manera de que las mismas puedan ser reemplazadas o actualizadas con muy pocos o casi ningún cambio en el código fuete de sus clases.
  • Desea escribir clases que dependan de clases cuyas implementaciones no son conocidas en tiempo de compilación.
  • Desea testar las clases aisladamente sin sus dependencias.
  • Desea desacoplar sus clases de ser responsables de localizar y gestionar el tiempo de vida de sus dependencias.

Técnicas de implementación

Según diversos enfoques, este patrón puede implementarse de diversas maneras. Entre las más conocidas tenemos:
  • Inyección de dependencias
  • Service Locutor
ioc2

Service Locator

Un Service Locator es un componente que contiene referencias a los servicios y encapsula la lógica que los localiza dichos servicios. Así, en nuestras clases, utilizamos el Service Locator para obtener instancias de los servicios que realmente necesitamos.
El Service Locator no instancia los servicios. Provee una manera de registrar servicios y mantener una referencia a dichos servicios. Luego de que el servicio es registrado, el Service Locator puede localizarlo.
El Service Locator debe proveer una forma de localizar un servicio sin especificar el tipo. Por ejemplo, puede usar una clave string o el tipo de interface. Esto permite un fácil reemplazo de la dependencia sin modificar el código fuente de la clase.
Es asunto de la implementación de esta forma de IoC, el determinar la forma en que se localizará el servicio requerido.

Inyección de dependencias

Una dependencia entre un componente y otro, puede establecerse estáticamente o en tiempo de compilación, o bien, dinámicamente o en tiempo de ejecución. Es en éste ultimo escenario es donde cabe el concepto de inyección, y para que esto fuera posible, debemos referenciar interfaces y no implementaciones directas.
En general, las dependencias son expresadas en términos de interfaces en lugar de clases concretas. Esto permite un rápido reemplazo de las implementaciones dependientes sin modificar el código fuente de la clase.
Lo que propone entonces la Inyección de dependencias, es no instanciar las dependencias explícitamente en su clase, sino que declarativamente expresarlas en la definición de la clase. La esencia de la inyección de las dependencias es contar con un componente capaz de obtener instancias validas de las dependencias del objeto y pasárselas durante la creación o inicialización del objeto.
ioc3
1. A necesita una referencia a B, pero no necesita saber como debe crear la instancia de B, solo quiere una referencia a ella.
2. B puede ser una interface, clase abstracta o clase concreta.
3. Antes de que una instancia de A sea usada, necesitara una referencia a una instancia de B.
Aquí no hay un alto acoplamiento entre A y B, ambas pueden cambiar internamente sin afectar a la otra. Los detalles de cómo se crea y gestiona un objeto B, no es decidido en la implementación de A. Es un framework IoC quien usa un método como setB() de A para inyectar luego a un objeto B.
Existen tres principales maneras de implementar la inyección de dependencias:

Inyección basada en Constructor

Las dependencias se inyectan utilizando un constructor con parámetros del objeto dependiente. Éste constructor recibe las dependencias como parámetros y las establece en los atributos del objeto.
Considerando un diseño de dos capas donde tenemos una capa de BusinessFacade y otra de BusinessLogic, la capa BusinessFacade depende de la BusinessLogic para operar correctamente. Todas las clases de lógica de negocio implementan la interface IBusinessLogic.
En la inyección basada en un constructor, se creará una instancia de BusinessFacade usando un constructor parametizado al cual se le pasará una referencia de un IBusinessLogic para poder inyectar la dependencia.
interface IBusinessLogic
{
//Some code
}
class ProductBL implements IBusinessLogic
{
//Some code
}
class CustomerBL implements IBusinessLogic
{
//Some code
}
public class BusinessFacade
{
private IBusinessLogic businessLogic;
public BusinessFacade(IBusinessLogic businessLogic)
{
this.businessLogic = businessLogic;
}
}
El objeto responsable de las dependencias realizará la inyección de la siguiente forma:
IBusinessLogic productBL = new ProductBL();
BusinessFacade businessFacade = new BusinessFacade(productBL);
La principal desventaja de la IoC basada en constructor es que una vez que la clase BusinessFacade es instanciada no podemos cambiar las dependencias inyectadas.

Inyección basada en métodos setters

En este tipo de IoC, se utiliza un método setters para inyectar una dependencia en el objeto que la requiere. Se invoca así al setter de cada dependencia y se le pasa como parámetro una referencia a la misma.
public class BusinessFacade
{
private IBusinessLogic businessLogic;
public setBusinessLogic(IBusinessLogic businessLogic)
{
this.businessLogic = businessLogic;
}
}
El objeto responsable de las dependencias realizará la inyección de la siguiente forma:
IBusinessLogic productBL = new ProductBL();
BusinessFacade businessFacade = new BusinessFacade();
businessFacade.setBusinessLogic(productBL);
La ventaja aquí es que uno puede cambiar la dependencia entre BusinessFacade y la implementación de IBusinessLogic luego de haber instanciado la clase BusinessFacade.
La desventaja es que un objeto con setters no puede ser inmutable y suele ser complicado determinar cuales son las dependencias que se necesitan y en que momento se las necesita. Se recomienda así utilizar IoC basada en constructor a menos que necesite cambiar la dependencia y sepa claramente los momentos en los cuales realizar estos cambios.
Otra desventaja es que al utilizar setters (necesarios para la inyección), estamos exponiendo las propiedades de un objeto al mundo exterior cuando en realidad no era un requerimiento de negocio hacerlo.

Inyección basada en interfaces

Aquí se utiliza una interfaz común que otras clases implementan para poderles luego inyectar dependencias. En el siguiente ejemplo, a toda clase que implemente IBusinessFacade se le podrá inyectar cualquier objeto que implemente IBusinessLogic mediante el método injectBLObject.
interface IBusinessLogic
{
//Some code
}
interface IBusinessFacade
{
public void injectBLObject (IBusinessLogic businessLogic);
}
class ProductBL implements IBusinessLogic
{
//Some code
}
class CustomerBL implements IBusinessLogic
{
//Some code
}
class BusinessFacade implements IBusinessFacade
{
private IBusinessLogic businessLogic;
public void injectBLObject (IBusinessLogic businessLogic)
{
this.businessLogic = businessLogic;
}
}
El objeto responsable de las dependencias realizará la inyección de la siguiente forma:
IBusinessLogic businessLogic = new ProductBL();
BusinessFacade businessFacade = new BusinessFacade();
businessFacade.injectBLObject(businessLogic);
Las tres formas de inyección presentadas, pasan una referencia a una implementación de IBusinessLogic más que un tipo particular de BusinessLogic. Esto presenta muchas ventajas, como lo declara Jeremy Weiskotten, un reconocido ingeniero de software de la empresa Kronos.
“Codificar contra interfaces bien definidas es la clave para alcanzar un menor acoplamiento. Acoplando un objeto a una interface en lugar de a una implementación específica, permite utilizar cualquier implementación con el mínimo cambio y riesgo”

Aplicabilidad

Cuando utilizar IoC

La inyección de dependencias no debería usarse siempre que una clase dependa de otra, sino más bien es efectiva en situaciones específicas como las siguientes:
  • Inyectar datos de configuración en un componente.
  • Inyectar la misma dependencia en varios componentes.
  • Inyectar diferentes implementaciones de la misma dependencia.
  • Inyectar la misma implementación en varias configuraciones
  • Se necesitan alguno de los servicios provistos por un contenedor.
La IoC no es necesaria si uno va a utilizar siempre la misma implementación de una dependencia o la misma configuración, o al menos, no reportará grandes beneficios en estos casos.

Contenedores

En pos de implementar el patrón IoC en alguna de sus variantes, existen los denominados contenedores de inyección de dependencias (CID), que son los componentes encargados de instanciar las dependencias y realizar las inyecciones necesarias entre todos los objetos y además gestionar sus respectivos ciclos de vida.
En cuanto a la instanciación e inyección, un CID se configura para especificarle que dependencias debe instanciar y donde deberá luego inyectarlas. Para la instanciación además, se debe definir el modo de instanciación, es decir, si se creará una nueva siempre que se lo requiera, o se reusará la instancia creada (singleton).
En cuanto a la gestión de los ciclos de vida de los objetos creados, implica que son capaces de administrar las diferentes etapas de la vida del componente (instanciación, configuración, eliminación).
El hecho de que el contenedor a veces mantenga una referencia a los componentes creados luego de la instanciación es lo que lo hace un contenedor.
No todos los objetos deben ser gestionados. El contenedor mantiene una referencia a aquellos objetos que son reusados para futuras inyecciones, como singletones. Cuando configuramos el contenedor para que siempre cree nuevas instancias, entonces éste se suele olvidar de dichos objetos creados, dejando la tarea al GC para recolectarlos luego de que no sean más usados.
Existen varios CID, según el lenguaje de programación que soportan, que modos de IoC soportan, etc.. Para Java tenemos el Butterfly Container, Spring, Pico Container, Guice, y otros.

Conclusión

La natural mutabilidad de las partes o módulos de un sistema, hace que el desarrollar software con mínimo acoplamiento entre sus componentes sea una necesidad mas que un mero requerimiento.
La popularidad y efectividad del patrón IoC en cualquiera de sus formas (Service Locator, Inyección de dependencias, etc.) se observa en la diversidad de frameworks y contenedores disponibles en diversos lenguajes.
En estos contextos, la aplicación del patrón IoC es una de las primeras decisiones que deben tomarse en el diseño de la arquitectura de un producto software.
Saludos

Gastón Guillerón
gguilleron@glnconsultora.com

Referencias

  • http://tutorials.jenkov.com/dependency-injection/index.html
  • http://geekexplains.blogspot.com/2008/12/spring-ioc-inversion-of-control-di.html
  • http://msdn.microsoft.com/en-us/library/cc707904.aspx
  • http://www.theserverside.com/news/thread.tss?thread_id=23358
  • http://www.devx.com/Java/Article/27583
  • http://dotnethitman.spaces.live.com/blog/cns!E149A8B1E1C25B14!267.entry
  • http://www.epidataconsulting.com/tikiwiki/tiki-index.php?page=Spring+IoC+Container#Inversion_of_Control
  • http://tutorials.jenkov.com/dependency-injection/when-to-use-dependency-injection.html
  • http://www.devx.com/dotnet/Article/34066/0/page/2

Introducción a Managed Extensibility Framework (MEF)

Qué es MEF y que te aporta

MEF es una tecnología que permite desarrollar aplicaciones extensibles. La gran ventaja que nos ofrece MEF es que no necesitamos diseñar la aplicación conociendo qué extensiones formaran parte de ella ni la implementación interna de las propias extensiones.
Por extensible nos referimos a que nuestra aplicación puede estar en producción y de forma dinámica añadir, reemplazar, eliminar las extensiones que tenemos sin necesidad ni de recompilar ni reiniciar la aplicación.
MEF viene con .NET Framework 4 en la librería: System.ComponentModel.Composition.

MEF vs IoC Container

Aunque pueda parecer que MEF e IoC  ofrecen la misma funcionalidad la diferencia consiste en que tratan de resolver problemas distintos.
El objetivo básico de un framework de IoC es el de ofrecer desacoplamiento entre componentes y nos resuelve dependencias que conocemos. Esto nos permite que nuestra aplicación sea modular y testeable.
En cambio, en MEF, el principal objetivo es la extensibilidad: el desacoplamiento es una consecuencia. Sabemos que las extensiones que se vayan a implementar cumplirán un contrato pero no sabremos si sólo habrá una extensión, muchas o ninguna.

Ejemplo: Extensión IHelloWorld

Vamos a ver un ejemplo de cómo consumir nuestras extensiones con MEF. El ejemplo es muy sencillo y únicamente tenemos una aplicación de consola que consumirá extensiones que nos devuelven el mensaje Hola Mundo en el idioma definido en la extensión.
Primero declaramos en el ensamblado Serrate.MEFDemo.HelloWorld.Interface el contrato que deben cumplir:
1namespace Serrate.MEFDemo.HelloWord.Interface
2{
3    /// <summary>
4    /// Contrato para extensiones
5    /// </summary>
6    public interface IHelloWorld
7    {
8        string GetMessage();
9    }
10}
Posteriormente en nuestra aplicación de consola Serrate.MEFDemo.HelloWorldApp tenemos la clase Consumer encargada de consumir, como no, las extensiones de terceros.
1namespace Serrate.MEFDemo.HelloWorldApp
2{
3    /// <summary>
4    /// Clase encargada de consumir nuestras extensiones
5    /// </summary>
6    public class Consumer
7    {
8        /// <summary>
9        /// Esta lista importará las extensiones que cumplan
10        /// nuestros requisitos
11        /// </summary>
12        [ImportMany]
13        public List<IHelloWorld> HelloWorldPlugins { get; set; }
14 
15        /// <summary>
16        /// Lectura de nuestras extensiones
17        /// </summary>
18        public void Read()
19        {
20            // Configuramos nuestro contenedor
21            this.Setup();
22 
23            // Recorremos la lista de extensiones
24            foreach (var plugin in HelloWorldPlugins)
25            {
26                Console.WriteLine(plugin.GetMessage());
27            }
28 
29            Console.ReadLine();
30        }
31 
32        private void Setup()
33        {
34            // a partir del directorio de la aplicación buscamos
35            // en una ruta relativa nuestro directorio de extensiones
36            string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
37            DirectoryInfo extensionsDirectory =
38                new DirectoryInfo(appDirectory + "..\\..\\..\\extensions");
39 
40            // creamos el catálogo a partir del directorio
41            var catalog = new DirectoryCatalog(extensionsDirectory.FullName);
42 
43            // componemos las extensiones para poderlas usar
44            var compositionContainer = new CompositionContainer(catalog);
45            compositionContainer.ComposeParts(this);
46        }
47    }
48}
Como podemos tener varias extensiones cumpliendo el mismo contrato, en nuestra aplicación declaramos una lista de este contrato, y la decoramos con el atributo [ImportMany]:
1/// <summary>
2/// Esta lista importará las extensiones que cumplan
3/// nuestros requisitos
4/// </summary>
5[ImportMany]
6public List<IHelloWorld> HelloWorldPlugins { get; set; }
Seguidamente podemos realizar la lectura de nuestras extensiones:
1/// <summary>
2/// Lectura de nuestras extensiones
3/// </summary>
4public void Read()
5{
6    // Configuramos nuestro contenedor
7    this.Setup();
8 
9    // Recorremos la lista de extensiones
10    foreach (var plugin in HelloWorldPlugins)
11    {
12        Console.WriteLine(plugin.GetMessage());
13    }
14 
15    Console.ReadLine();
16}
En el método Setup indicamos el directorio de nuestras extensiones y realizamos la carga de éstas:
1private void Setup()
2{
3    // a partir del directorio de la aplicación buscamos
4    // en una ruta relativa nuestro directorio de extensiones
5    string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
6    DirectoryInfo extensionsDirectory =
7        new DirectoryInfo(appDirectory + "..\\..\\..\\extensions");
8 
9    // creamos el catálogo a partir del directorio
10    var catalog = new DirectoryCatalog(extensionsDirectory.FullName);
11 
12    // componemos las extensiones para poderlas usar
13    var compositionContainer = new CompositionContainer(catalog);
14    compositionContainer.ComposeParts(this);
15}
Finalmente, ya sólo nos hace falta crear nuestras extensiones que realizarán el trabajo duro. Indicaremos que las extensiones son exportables mediante el atributo [Export]
Crearemos el ensamblado Serrate.MEFDemo.Plugin.ES y allí tendremos nuestra clase que implementará el contrato:
1namespace Serrate.MEFDemo.Plugin.ES
2{
3    [Export(typeof(IHelloWorld))]
4    public class HolaMundo : IHelloWorld
5    {
6        public string GetMessage()
7        {
8            return "Hola Mundo";
9        }
10    }
11}
En otro ensamblado Serrate.MEFDemo.Plugin.CA tendremos definida otra extensión:
1namespace Serrate.MEFDemo.Plugin.CA
2{
3    [Export(typeof(IHelloWorld))]
4    public class HolaMon : IHelloWorld
5    {
6        public string GetMessage()
7        {
8            return "Hola Món";
9        }
10    }
11}
Si colocamos las librerías de nuestras extensiones en la carpeta que espera nuestra aplicación, al ejecutarla ya nos saldrá por pantalla el resultado esperado:
> Hola Mundo
> Hola Món
En esta introducción hemos visto como utilizar MEF para que nuestra aplicación pueda ser extendida por nosotros mismos o por terceros de forma realmente sencilla.