Saturday, June 7, 2008

The Forced Hiatus and the Faulty Laptop.

Today I'll be sending my laptop back to the manufacturer for repairs, and that means all my development work (including LinFu) will be effectively suspended until I can get this issue resolved. According to the manufacturer, the turnaround time should take about 7-10 business days (roughly two calendar weeks).


Meanwhile, the only 'hardware' that I'll have at my disposal will be Pen and Paper (tm), and I still have more than a few things lined up on the LinFu drawing board, even without a compiler. Development is going to screech to a halt in the next few weeks, and then I'll be back with some pretty hefty updates to LinFu. Stay tuned :)

Monday, March 31, 2008

Optimistic vs. Pessimistic Design: Which one do you practice?

Lately, I've been noticing a trend in some of the object-relational mapping (ORM) tools in the market place, and the pattern that's emerging is interesting, to say the least.

In general, their feature sets seem to fall into one of these categories:

Pessimistic Design - The designers don't know which features their users will actually use, so they decide to implement nearly *every* possible mapping feature and then leave the end-user to decide how to use their ORM. This approach gives the broadest amount of features but sacrifices simplicity for documentation.

Optimistic Design - The designers assume that you're only going to use 20% of its functionality and implement 80% of the features that would be used in 100% of the mapping cases. They provide you with a general framework for the mapping and the change tracking, and they leave it to you (as the end user) to customize it to your needs. This approach makes the ORM easy to use, but the tradeoff is that it only implements a minimal feature set. The upside to this is that the code is so easy to use that it requires little to no documentation at all. It's practically self-documenting code.

From what I've seen so far, a lot of ORM implement pessimistic design, but very few actually implement the optimistic approach. Do the pessimistic designers assume that their end-users are incapable of implementing their own features, or is an optimistic approach too minimalistic to be useful at all?

With this in mind, it's quite tempting for me to write an ORM that uses an optimistic design approach. There might be some value in having an ORM that lets you do your job in a few minutes without having to sift through dozens of pages of tutorials. I'm a big pundit for large feature sets, but in the end, there's no substitute for pure simplicity.

Wednesday, March 19, 2008

LinFu.DynamicModel, MxClone, and the Art of Adaptive Object Models

I've done it! :) Both the LinFu.DynamicModel and the MxClone (the MyXaml Engine Clone) libraries are ready for production use, and I can't wait to get started on writing the CP articles for both libraries.

A Tale of Two Approaches

As I mentioned in previous posts, LinFu.DynamicModel allows you to dynamically create an entire object model in memory at runtime without having to recompile your application. With LinFu.DynamicModel, you can either construct the model directly through code, or you can use the MxClone to create the model for you, using XML markup. I'll briefly go over each approach in the following sections, but before I do that, let's take a look at the interface implementation that we're going to dynamically generate:

A Canonical Approach: The Person Interface

Let's suppose that I wanted to dynamically create a dynamic type that looks like the following interface:

public interface IPerson
{
int Age { get; set; }
string Name { get; set; }
}

Using LinFu.DynamicModel in Your Code

Here's how you can dynamically create a type that implements the IPerson interface:

// TypeSpec objects are type descriptions that can be modified at runtime
TypeSpec personSpec = new TypeSpec()
{
Name="PersonType",

// Notice the strongly-typed properties
Properties =
{
new Property<int>("Age"),
new Property<string>("Name")
},
};

// This will return true
bool isPerson = personSpec.LooksLike<IPerson>();
var person = personSpec.CreateDuck<IPerson>();

// Use the person object just like any other POCO
person.Age = 18;
person.Name = "Me";
// ...


Thanks to C#'s 3.0 new language features, you can easily create a model in memory with LinFu in relatively few lines of code. What makes this particularly interesting, however, is the fact that as the given TypeSpec changes, all of the IPerson instances that rely on that TypeSpec automatically "change" their behavior to match the newly-modified Person TypeSpec.

Using LinFu.DynamicModel with MxClone

Needless to say, there's a myriad of things you can do with this sort of technology, but it gets better--you can describe the same model through XML, using a MyXaml-style syntax:

<?xml version="1.0" encoding="utf-8"?>
<Root xmlns="LinFu.Reflection.Extensions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
xmlns:def="Definition" xmlns:set="Setters">
<TypeSpec def:Name="PersonType" Name="PersonType">
<Properties>
<PropertySpec PropertyName="Name"
PropertyType="System.String">
<set:Behavior>
<PropertyBag/>
</set:Behavior>
</PropertySpec>
<PropertySpec PropertyName="Age"
PropertyType="System.Int32">
<set:Behavior>
<PropertyBag/>
</set:Behavior>
</PropertySpec>

</Properties>
</TypeSpec>

</Root>


As you can see, the XML syntax for MxClone is similar to MyXaml, with the exception of the set:Behavior element. MxClone allows you to assign object references to properties without having to give it a specific reference name (e.g., {SomeName}), and in this case, the set:Behavior element means that I'm assigning an object reference of type 'PropertyBag' to a property named "Behavior" on the PropertySpec type. (The PropertyBag class, in turn, is responsible for maintaining the state of each property on every given type instance--but for now, I'll save that for the upcoming LinFu article on CP)

In essence, MxClone is actually constructing the same TypeSpec in memory using XML markup. Having the model specified in XML allows you to change it at runtime without recompiling the application, and that could come in handy if you need to change your business model with minimal downtime. Anyway, back to the markup...

From XML to TypeSpec, in 15 Lines of Code

Now that we have the XML markup, the next thing you might be wondering about is the client code: exactly how do you convert that markup into a running TypeSpec? Here's how you do it:


// Load the engine into the container
string directory = AppDomain.CurrentDomain.BaseDirectory;
SimpleContainer container = new SimpleContainer();
Loader loader = new Loader(container);
loader.LoadDirectory(directory, "*.dll");

IMxEngine engine = container.GetService();

// The instance holder will
// store the object graph once
// it's been instantiated by the engine
IInstanceHolder holder = new DefaultInstanceHolder();
string file = @"C:\YourDirectory\SimpleTypeSpecSample.xml";
engine.Execute(file, holder);

TypeSpec spec = holder.GetInstance("PersonType");
bool isPerson = spec.LooksLike();

// Use the person class normally
IPerson person = spec.CreateDuck();
person.Age = 18;
person.Name = "Me";


In the example above, I used the Simple.IOC container to instantiate the MxClone Engine. The engine, in turn, converted the XML markup into a working Person TypeSpec, and lastly, I used that same TypeSpec instance to create the IPerson instance. It's just that simple. :)

Conclusion

As you can see, there's quite a bit of development going on with LinFu.DynamicModel and LinFu.MxClone, and like everything else in the LinFu project, it will all remain under the LGPL license. I've put my heart and soul into this project, and hopefully, everyone will see that once the next set of LinFu articles comes out on CP. Stay tuned!

Monday, March 17, 2008

Using Selective Method Weaving for LinFu.AOP

A while back, someone asked me if there was a way to make LinFu.AOP weave only certain types of methods and properties, and at the time, LinFu.AOP wasn't capable of doing that--that is, until now.

Here's how you do it. All you need to do is provide your own custom implementation of an interface named IMethodFilter and put that implementation in the same directory as LinFu.Aop.Weavers.Cecil.dll, and you're good to go. Here's a simple example:

[Implements(typeof(IMethodFilter), LifecycleType.OncePerRequest)]
public class MySampleCustomFilter : IMethodFilter
{
public bool ShouldWeave(MethodDefinition method)
{
// Intercept only public methods
return method.IsPublic;
}

}

All you have to do is put that in a separate DLL and make sure that the assembly is located in the same directory as LinFu.Aop.Weavers.dll, and you can customize it to your heart's content. It's just that simple. Enjoy!

Thursday, March 13, 2008

A Peek at LinFu.DynamicObject

Although it's been quite a while since my last post, LinFu has been coming along quite nicely with some recent additions. In the past month, I've managed to create two new things for LinFu:

  • A Dynamic Typing System for LinFu.DynamicObject, and
  • A MyXaml clone that will deserialize the DynamicModel from disk and load it into memory.


The Current State of Affairs

In LinFu's current state, you can only dynamically add properties and methods to DynamicObjects on a per-instance basis. Currently, there's no way to create a prototype for an entire set of DynamicObject instances and have all of those instances share the same conceptual prototype. For example, suppose that I wanted to create a Person type that looks something like this:

public interface IPerson
{
string Name { get; set; }
int Age { get; set; }
}

In order to have a set of dynamic objects emulate a IPerson instance, I would have to manually generate a Name and an Age property on each dynamic object that I needed to use. While such a scenario might be acceptable if I only needed to use a few DynamicObjects, the story starts to become quite different if that small few suddenly becomes a few hundred thousand. Suffice to say, there's quite a cost in having to set up a couple hundred thousand dynamic objects in memory at runtime. There must be a better way to do this, and thus, LinFu.DynamicModel was born.

Build Your Own Model, All at Runtime

LinFu.DynamicModel allows you to create an in-memory type specification (or prototype) of what you want your DynamicObjects to look like. You can add or remove methods and properties to this specification at runtime, all without having to create a single DynamicObject. Any DynamicObject that is attached to that type specification will effectively have all the properties and methods of that spec. The best part about all this is that all changes you make to a spec at runtime will be reflected in every single DynamicObject that uses that type specification.

For example, let's suppose that I wanted to create an implementation of the IPerson interface and have two DynamicObjects share the same conceptual Person type. Here's how it would look like:

DynamicObject firstPerson = new DynamicObject();
DynamicObject secondPerson = new DynamicObject();

// Both of these LooksLike() calls will return false
// since IPerson has yet to be implemented
Console.WriteLine("Object #1: IsPerson? {0}", firstPerson.LooksLike());
Console.WriteLine("Object #2: IsPerson? {0}", secondPerson.LooksLike());

// Create a person type with only the Name property implemented
TypeSpec personSpec = new TypeSpec();
personSpec.AddProperty("Name", typeof(string));


DynamicType personType = new DynamicType(personSpec);

// Make both DynamicObjects act like the person type
firstPerson += personType;
secondPerson += personType;

// Note: This still will return false since we haven't implemented the Age property
Console.WriteLine("Object #1: IsPerson? {0}", firstPerson.LooksLike());
Console.WriteLine("Object #2: IsPerson? {0}", secondPerson.LooksLike());

// Finally, implement the age property so that both types look like an IPerson
personSpec.AddProperty("Age", typeof(int));


// Note: Both DynamicObject instance calls to LooksLike() will now return true
// since the type they refer to now implements IPerson
Console.WriteLine("Object #1: IsPerson? {0}", firstPerson.LooksLike());
Console.WriteLine("Object #2: IsPerson? {0}", secondPerson.LooksLike());

// Use both instances normally as IPerson instances...
IPerson first = firstPerson.CreateDuck();
IPerson second = secondPerson.CreateDuck();

// ...

As you probably noticed from the example above, the only thing I needed to do was modify the TypeSpec instance and both DynamicObjects automatically changed their behavior to match the given TypeSpec. In theory, this will allow you to effectively generate an entire object model in memory without having to recompile the application. In fact, the only thing you would need at this point is a reliable way to deserialize the object model from disk. At first, using the .NET BCL's serialization mechanisms might be the easiest way to do this, but LinFu.DynamicModel's metamodel heavily relies on interfaces to provide each method and property implementation, and those interfaces cannot be serialized to disk by the classes in the System.Runtime.Serialization namespace.

Legally Infeasible

Now, since MyXaml is very good at instantiating object graphs, and LinFu's DynamicModel is nothing but a metamodel object graph, the next logical step would be to use MyXaml, but there's just one problem--MyXaml is licensed under the GPL, not the LGPL, which means that MyXaml can't be used in commercial applications unless you obtain a commercial license from Marc Clifton, or you publish the source code to your own commercial applications. Since I'm committed to making all of LinFu available under the LGPL, I had no choice but to write my own MyXaml engine from scratch, and hopefully, I can cover that in my next blog post. For now, all I can say about my unnamed MyXaml clone is that it's some of the best code that I've ever written, and this one is definitely worth the wait.

In the meantime, this should whet our appetite for what's to come in LinFu, and the future looks bright indeed.

Stay tuned!

Wednesday, February 6, 2008

LinFu.DynamicObject and Dynamic Object Models

I've been playing around with LinFu.DynamicObject and I've discovered a way to implement a dynamic typing system that can be changed at runtime. That means that with LinFu.DynamicObject, you can assign it to a particular DynamicType instance and any DynamicObjects that depend on that same instance will actually change their methods and properties at runtime to match that particular DynamicType!

Adaptive Object Models, anyone? :)

Dynamic Method Dispatch is one thing that LinFu can do very well, and pretty soon, you'll be able to reconfigure an entire object model in memory without having to recompile the application.

Suffice to say, things are going to get interesting with LinFu as the series of articles progresses.

Stay tuned!

Thursday, January 31, 2008

The Model, View, and (Virtual) Presenter Pattern



One of the greatest weaknesses of the
MVP/MVC pattern is that although the the model is completely separated from the view (and vice-versa), the view in the MVP pattern has to have a concrete dependency on its corresponding Presenter in order to function. At first, there doesn't seem to be a way to completely isolate all three components of the MVP pattern from each other, given that the view has to have a reference to a concrete presenter. The presenter, on the other hand, knows nothing about the concrete view, other than the IView interface that is implemented by the view itself; it's a one way dependency, and yet, something just doesn't 'feel' right here...

The Epiphany


...and then that's when the questions started to hit me:
Does the presenter even have to be a concrete presenter at all? Is it possible to replace a concrete presenter with an interface type, and what would that interface look like? Are all presenters the same, or do they just all represent some sort of abstract concept that can't be centralized into a single common class?

My proposal for changing the MVP pattern is this: What if we convert the concept of the presenter from a concrete class to an abstract metaclass? If we change the presenter from a concrete class to an abstract implementation of a concept, we can effectively eliminate the dependency between all three parts of the MVP triad. It might sound complex, but the implementation is actually quite simple. In this variant of the MVP pattern, we can completely eliminate the view's dependency on a concrete presenter by converting the concrete presenter dependency into a collection of interfaces that the view requires in order to function.

A Quixotic Attempt


A naive approach would be to try to find a common interface to be implemented by presenters, but this poses a problem--no two presenters will ever be exactly alike. A presenter that will handle a list view won't always have the same interface as a presenter that handles a date field. In addition, there might be presenters which might hold some business or validation logic that other presenters might not necessarily share. In other words, we're dealing with a situation where each presenter interface allmust be heterogenous for each view type, and that makes it difficult to group all of the presenters into a single interface that could be used by each view type.

Dead End?

At first, it might seem like we have no choice but to make each presenter concrete and customize each one of them to fit their corresponding views--but what if we refactored each one of these concrete presenters into multiple interface dependencies for each view? If you think about it, a concrete presenter is nothing but a collection of different responsibilities assigned to a concrete interface. For example, a DatePresenter class might have a few methods that check if the date value presented in the view is valid. The same DatePresenter class also might have methods which can persist the date value to the database. The crux of the concrete presenter in the MVP pattern is that the date view relies on this same DatePresenter to control its behavior. There's a one-way separation between the view and the presenter, and there has to be a way to completely isolate the presenter from the view itself.

An Unnecessary Coupling

A view (for the most part) doesn't need a reference to a concrete presenter class as much as it needs a reference to the interfaces and responsibilities that each one of those interfaces represent. In fact, if I were to refactor a concrete presenter, extract each one of its interfaces, and have each one of those interfaces represent a responsibility that the target view requires, it almost seems like I've converted the concrete presenter into a de facto service container.

Each presenter responsibility corresponds to a service, and each service corresponds to an interface type. Since no two presenters are alike, one could even say that each presenter has a list of services that it offers to each view. So for me, the next logical question is this: If concrete presenters are nothing but de facto service containers, why not use a real service container (aka IoC container) and ditch the concrete dependency altogether?

If a concrete presenter is actually nothing but a degenerate IoC container in disguise, then I can take each one of the view types and replace their concrete presenter dependencies with a single dependency--a dependency on real IoC container by itself. What makes this interesting is that in this variant of the MVP pattern, the 'P' in the MVP pattern no longer exists as a concrete class. The view's concrete dependency on the presenter has been supplanted by interface dependencies supplied by an IoC container. Using this scheme, the view knows nothing about the actual presenter concrete class, and the presenter knows nothing about the concrete view class. As an added bonus, we can even separate the presenter from the concrete model by having the presenter rely on interfaces supplied by the model, and vice versa. The best part about all this is that (aside from the interface dependencies) all three parts of the MVP triad are completely isolated from one another. The only dependency that all three parts of the MV(P) pattern share is the IoC container itself, and since most IoC containers are easily configurable by design (namely LinFu), this dynamically gives us complete control over all the dependencies of a given application...

Note: So far, all of this is just theory, and I have to write it down somewhere before I forget it. I think this pattern can help quite a lot of people, and hopefully I can test it soon.