Mostrando entradas con la etiqueta composicionOrientedPrograming. Mostrar todas las entradas
Mostrando entradas con la etiqueta composicionOrientedPrograming. Mostrar todas las entradas

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.

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.