AJ's blog

April 29, 2007

InFactoring the Architecture

As already mentioned the I use a factory within an application architecture as a means for layer separation. The „Layer“ in “layer separation” refers to the omnipresent 3-tier, 3+-tier, multi-layer, what-ever-you-call-it-layer approach that is used in one or the other incarnation for todays web applications and services. Let’s assume the most basic incarnation for a web application, i.e. 3 classical layers.

I described the understanding of the term “factory” in my last post, now let’s see how to employ it.

The architecture

I‘ll spare you (and me) the boring picture of three blocks sitting on top of each other. Curiously no application is built purely this way, anyway. But let’s go ahead and structure the core layers and add the necessary vertical layers.

architecture.gif

Still very simple. Just for the bookkeeping: “Presentation” stands for the Web Application (the bunch of config files, .aspx files, .css files, etc.) and I assumed some kind of MVC (or related) pattern for the UI layer, implemented in the “Controller” block.
“Data Structures” contains the [please fill in your favourite choice of Data Sets, Value Objects, Entity Objects, or in whatever shape your data flows across the data layer, business layer, and presentation layer].
“Utils & Factory” contains orthogonal services, e.g. helper classes, tracing, error handling, and – hey! – our factory would reside here.

The factory

Let’s stress the fact that the business layer and the data access layer have a small interface block. This block is meant to be the only visible part of the respective layer. No bypassing allowed! Thinking of code, this part would be made out of C# interfaces and layer specific exceptions (VB.NET? No, sorry, you can’t do that in VB 😉 ). The implementation block of the layer contains the actual implementation classes and whatever else is needed.

The interface blocks are also the place where the factory enters the stage: The calling layer will never access these implementation classes directly, in fact it should not even know them. Rather it will ask the factory for an object that supports one particular interface. The factory will create the respective object and return it. E.g. the presentation layer would access some kind of customer information like this:

1. The business layer defines a customer service interface and a correponding implementation (within the respective blocks.

2. The business service is registered to be used by the factory with the type name of the interface as key:

<typeNames>
    <add
        key=“SDX.MyApp.Business.Contract.ICustomerService”
   
    value=“SDX.MyApp.Business.Components.CustomerService, SDX.MyApp.Business.Components” />
    … 
</typeNames> 

3. The presentation code uses the factory to gain access to the business service: 

ICustomerService o= Factory<ICustomerService>.Create();

In case you didn’t notice: I just repeated the sample from my last post. It’s that simple — and yet, it still introduces additional complexity and error conditions.

The bennefits

So, what would be gained by this approach (other than complicating object instantiation and satisfying the play instinct of a certain architect 😉 )? Well, there are very different aspects and they vary depending on the project life cycle:

Think of the early project stages…

The “Best Case” starting a development project would probably be to have a business specification with detailed descriptions. Descriptions that you can analyze to determine the business data and the operations upon this data … . In other words, you design the business entities and the (business) interface. In other words — since this also depends on the demands of the presentation layer — you do some kind of negotiation between those two layers — a process called contracting in the SOA world. Yes, we just introduced some SOA concepts into application design. The interfaces are being designed prior to the implementation and in close negotiation between the responsible developers of the respective layers. That should yield better results than ad-hoc implementations (and you may take that as understatement).

Once those interfaces are in place the different layers can be developed independently from each other. The presentation layer team can start to develop the frontend using some simulation classes as long as the business layer team is still working on the implementation. The business layer team can use unit tests as frontend simulation. Thus we also reduced team dependencies.

Think of development …

During development you will encounter additional orthogonal (cross cutting) behaviour, e.g. caching, routing, or security. Take caching as example. If every read or write access of customers is done via (exactly) one business service interface, this interface defines when to cache and when to invalidate cached data. Rather than putting the caching code in the business service (and spoiling the business logic) or in the presentation layer (sprinkling it all over the layer), we can inject it between the two layers, using a pattern called interception.

For example:

<typeNames>
    <add
        key=“SDX.MyApp.Business.Contract.ICustomerService”
   
    value=“SDX.MyApp.Business.Components.CachedCustomerService, SDX.MyApp.Business.Components” />
    <add
        key=“SDX.MyApp.Business.Contract.ICustomerService-CACHED
   
    value=“SDX.MyApp.Business.Components.CustomerService, SDX.MyApp.Business.Components” />
    … 
</typeNames> 

And the CachedCustomerService looks somewhat like this:

public ICustomerService Service
{
    get
    {
        if (_service==null)
        {
            // create the real service
           string key= typeof(ICustomerService).FullName+“-CACHED”;
            _service = Factory<ICustomerService>.CreateAlias(key);
        }
        return _service;
    }
}

public IList<Customer> GetCustomerList(…)
{
    string key = “CustomerList-“ + …;
    
    IList<Customer> ret = HttpContext.Current.Cache[key] as IList<Customer>;
    if (ret == null)
    {
        // call the real service
        ret = Service.GetCustomerList(…);
        HttpContext.Current.Cache[key] = ret;
    }
    return ret;
}

This way we have introduced caching without the need to change either the presentation layer or the business logic. In fact, neither layer is even aware that there is a man-in-the-middle.

As a side note: The idea of „interceptors“ is nothing new. MTS/COM+ used call interception to add runtime behaviour (e.g. transactions and security) to existing interfaces. The Policy Injection Application Block does something similar, using remoting proxies.

Other features that could be added this way include tracing, data tracking, performance counting, error handling, call routing and other infrastructure services. Implementing these things as interceptors rather than within the layers provides flexibility and also promotes separation of concerns.

Think of testing …

The two patterns we have used so far — simulators and interceptors — can be used for testing as well. Simulators (or more appropriate mock objects) can easily replace real implementations for component tests. Interceptors can be used to induce simulated error conditions that are hard to create i.r.l.. (You wouldn’t crash you disk drive on purpose, would you?).

The limits

Of course this approach has weak spots and does not fit in any situation. I found it particullarly valuable on the presentation layer/business layer boundary when working with entity objects of some kind. Realizing the same bennefit between business layer and data access layer may be harder, though. An object mapper for example may be reluctant to fit into a clean layer structure, DataSets also carry data access logic enough to question the need for a layer with a service like interface. Real simple applications (i.e. nothing more than a simple database frontent) with little to no business logik will probably contain the same interfaces as business interfaces as well as data access interfaces, and the business layer will simply route any call to the data access layer. Why go through that trouble anyway? (Other than my experience that no applications stays that simple.)

This approach also profits from project teams of a certain size that have their responsibilities clearly separated horizontaly, aligned to layers, and assigned to different people (although I still like the contracting part even in a one-man show). It may not work so well if you have a vertical separation (aligned to business features).

Anyway, I’ve used this approach in small and mid-sized projects and it definitely payed off. Big projects need some additional thoughts but the principle still holds.

The next post will talk about using a factory for framework extensions points.

That’s all for now folks,
AJ.NET

kick it on DotNetKicks.com

April 21, 2007

Building the factory

Filed under: .NET, .NET Framework, C#, Software Architecture, Software Development — ajdotnet @ 4:11 pm

I hope my last post left you curious enough to come back 😉 . Before diving into the patterns I mentioned, I need to talk a bit about factories. Pave the way, so to speak.

I’ll assume that you know what a factory is — if smoking chimneys cross you mind you may leave right now 😉 — but since factories and the related patterns come in various flavours I should clarify what I define as „a Factory“ (if only for this post):
To put it simply: A factory is an object that takes a name (somehow describing the object instance I need) and returns a reference to an object or interface. Period. Well, OK, let’s assume there is some configuration file that maps names to types.

In more detail…

Since our factory shall take names and map them to types it will need some kind of dictionary, presumably supplied as config file, say something like this:

<typeNames>
   
<add key=“Name1” value=“Namspace1.Type1, Assembly1” />
    <add key=“Name2” value=“Namspace2.Type2, Assembly2” />
    …
</typeNames> 

Once we have the type, we need to create an object. In .NET creating objects dynamically should be done via the Activator class.

Activator “Contains methods to create types of objects locally or remotely, or obtain references to existing remote objects.” and is the recommended way to do just that. The AppDomain class also contains methods to create objects, as do other classes, but they usually call Activator themselves.

It is also possible to invoke the constructor directly via reflection. This is however not recommended.

Assuming the configuration has been loaded and put in some dictionaries, the core method of our homegrown factory looks somewhat like this (error handling omitted for brevity):

public object Create(string name)
{
    string assembly= _nameToAssembly[name];
    string type= _nameToType[name];
    ObjectHandle handle = Activator.CreateInstance(assembly, type);
    return handle.Unwrap();
}

The usage would look like this (assuming a respective singleton implementation of the factory):

// typeless
object o= Factory.Instance.Create(“Name1”);
// typed access
IMyInterface t= (IMyInterfacse)Factory.Instance.Create(“Name2”);

Conceptually there is really nothing more to it. Of course some code to fill the hash tables and some error handling, but that’s all. Well, that’s all that’s needed for the purposes I have currently in mind, but certainly not all that is possible. Let’s look at some enhancements.

Type safety

The first improvements to come up with are type safety and getting rid of the name argument, as it is prone to typos. A common use case for the factory is as follows: I have an interface and need an object that implements this interface. Wherever and whenever I ask for an implementation of that interface I get an object of a certain type — configurable but nevertheless always of the same type. In other words, the interface type is in itself a sufficient key and a type safe helper method taking that into account may look like this:

public static class Factory<ObjectType>

    static public ObjectType Create() 
    { 
        return (ObjectType)Factory.Instance.Create(typeof(ObjectType).FullName); 
    }
}

Complemented with a configuration that mapps interface type names to implementation classes:

<typeNames>
    <add
        key=“SDX.MyApp.Business.Contract.IAccountService”
       
value=“SDX.MyApp.Business.Components.AccountService, SDX.MyApp.Business.Components” /> 
    <add
        key=“SDX.MyApp.Business.Contract.ICustomerService”
   
    value=“SDX.MyApp.Business.Components.CustomerService, SDX.MyApp.Business.Components” />
    … 
</typeNames> 

The usage would now be more convenient:

IMyInterface o= Factory<IMyInterface>.Create();

Other improvements

The following improvements are definitely for more sophisticated usage scenarios than the ones I have in mind. But since this post is dedicated to factories in general I think I should to mention them anyway.

Here are some strategies to change or improve the object creation and initialization:

  • The factory could decide not to create a new object with every call, rather it could return the previously created instance again (effectively implementing a singleton mechanism). This requires the object to be reentrant and stateless, but if that’s the case, this will be a big improvement in terms of memory and performance.
     
  • A pooling approach could be implemented for objects that are particular expensive to create. It would require a base class that would implement IDisposable in a way that the object is not destructed but put back into the pool.
     
  • Talking about performance, creating objects dynamically is not exactly the most efficient thing to do. In fact it takes about 10^3 times more time than direct calls to new. If objects knew themselves how to create new instances of the same type (which is something ICloneable could help with), the factory could leverage this to implement a prototype mechanism: When an object is requested for the first time, a prototype instance is created dynamically and stored in an internal list. Rather than returning it, it is asked to create a new instance (efficiently via the mentioned interface) which is returned. Subsequent calls will use the prototype in the same way, resulting in a big performance boost for objects that are requested quite often. 
     
  • It is possible to specify not only the type in the config file, but also constructor parameters. These parameters could reference other objects also configured to be created by the factory. This would result in not only one object being created but a whole object graph. But this is no little amount of work to do and exactly what factory frameworks do.

Factory frameworks

If the last suggestion regarding constructor arguments in the config file is something you like, then Spring.NET may be the tool for you. It supports not only constructor arguments, but property setters as well. It handles references to other configured objects and some other cases, such as collections. And it supports the singleton mechanism out of the box (as I am painfully aware of). It lacks prototype or pooling support, but that could easily be build on top of it (as on every other factory framework).
On other hand, Spring.NET (when I last looked at it) does not follow the recommendation to create objects via the Activator class. Rather it tries to find an appropriate constructor (which does not always succeed) and invoke it directly. It also creates all singleton objects right away, which may cause problems of its own.

Short factory framework list:

Lastly let me point out that if your demands are as simple as described in the first part of this post, it is perfectly feasible to write a factory yourself. It won’t take weeks and it certainly has the benefit of not introducing external dependencies. OK, and it might be fun, too. 

In my next post I will employ the factory as a means for layer separation and I will add some additional patterns built on top of a factory. This should (hopefully) highlight the bennefits of using a factory.

That’s all for now folks,
AJ.NET

kick it on DotNetKicks.com

April 13, 2007

The factory factor

Filed under: .NET, .NET Framework, Software Architecture, Software Development — ajdotnet @ 9:48 pm

Lately dependency injection has become a popular topic within the developer community. This may be caused (or be the cause for – a bit like chicken and egg) by the availability of respective containers. One of the first broadly used containers was probably Spring.NET (a .NET port of the java Spring Framework), the castle project came to my attention a few times, and the latest addition is the Policy Injection Application Block (PIAB) as part of the Enterprise Library 3.0 (Microsoft patterns & practices group).

If you are new to dependency injection, the castle project “getting started” does a good job of highlighting the gist. Since the PIAB is a relatively new addition to the Enterprise Library (and came quite as a surprise) you may want to have a look at the announcement with a general introduction or some implementation details.

Dependency injection as a basic concept that has its value on its own, yet it is also tied to some other concepts, namely factories (the usual way to realize dependency injection) and aspect oriented programming (AOP, aspects being just special dependencies to inject).

I have to admit that I am not exactly a big fan of AOP (to say the least). And dependency injection in all its broad beauty requires some real hard thinking during design, discipline during development, and a sound understanding of concept and design during maintenance. Some of these demands may be in short supply — which is neither surprising nor exactly a bad thing; different developers (especially corporate developers) simply have different backgrounds and different topic priorities. Therefore, despite the technical fanciness and the fact that dependency injection can boost flexibility, I really need a compelling reason to employ it.

Lower one’s sights

So what if dependency injection is considered too complex in a certain situation? Are we back to hardcoding? Certainly not! Enter factories.

I am a big fan of factories. Factories are a well know pattern since the advent of patterns in public awareness. They also have (the potential to have) more impact on software architecture than most other basic patterns. Did I mention that they may lay the foundation for more complex patterns, such as dependency injection and AOP?

I have used factories of a certain kind to great benefit with different patterns. Actually these patterns can be seen as degraded variants of dependency injection. (They may also have characteristics of AOP, but I won’t admit that 🙂 ). The primary purposes I use them for are:

  1. Layer separation
  2. (Framework) Extension points

Despite the fact that the actual factory patterns I use are quite simple and quite easy to grasp, my approach has several benefits, e.g.:

  • Better layer interfaces/layer separation/separation of concerns
  • The easy employment of simulators and mock objects allows independent development of layers and better testability
  • “Chaining” or “call interception” (if needed!) can be used to add orthogonal functionality such as caching. Actually this works exactly like described in the PIAB, albeit not with tool support.
  • The possibility to adorn common features with application specific features.

Of course all this (and probably more) can be done with fully fledged dependency injection. But at the cost of more complexity (and container dependency may be an issue, too). (And to prevent angry comments: I’m not saying dependency injection is bad — Au contraire! — I’m just presenting an alternative approach.)

I’m going to dig into the details in the following posts, concepts and code. But not today.

That’s all for now folks,
AJ.NET

kick it on DotNetKicks.com

April 1, 2007

Those who would give up…

Filed under: Miscellaneous — ajdotnet @ 1:48 pm

European Parliament in Strasbourg

“Those who would give up essential liberty to purchase a little temporary safety deserve neither liberty nor safety.”
Benjamin Franklin

“The basis of a democratic state is liberty.”
— Aristotle

“Homo homini lupus”
Thomas Hobbes

Something not to be forgotten…
AJ.NET

Blog at WordPress.com.