Pages: Prev 1 2 3 4 5 6 7 Next
– page 4

Agile & Lean Software Development Management

deep thoughts on doing real work

image

Now it is time to generate some business entities from a model.

Suppose we have a simplified model with just one entity called Course. It has an unique identifier CourseID and a searchable and displayable attribute called CourseName.

To generate source code the model is injected into the following template.

image

The resulting generated code will look like this:

public class Course
{
    public int m_CourseID;
    public string m_CourseName;

    public int CourseID
    {
        get
        {
            return m_CourseID;
        }
        set
        {
            if (value != m_CourseID)
            {
                m_CourseID = value;
            }
        }
    }

    public string CourseName
    {
        get
        {
            return m_CourseName;
        }
        set
        {
            if (value != m_CourseName)
            {
                m_CourseName = value;
            }
        }
    }
}

That’s all.

imageThe Search-Engine pattern is a simple, but powerful pattern. The user provides some sort of search phrase and the search engine returns all matches found in a data store. Next, the user browses the results to select the one she is looking for. When selected details are shown. This is exactly how Google (and other search engines) works.Datamodel

This pattern is also very useful for maintenance of simple data normally found in an information system. 

To apply this pattern to entities under maintenance, they have to fulfill some criteria. The entity must be:

  1. searchable
  2. able to return displayable results
  3. identified by a unique key

The entities in the model shown right fulfill these criteria. They all have a unique identifier. They are searchable through their name, which is also used for displaying in the search results.

When looking in more detail, the entities in the simplified model look very similar. This makes them excellent candidates for a generic code-generated maintenance solution.

O/R mapping is a programming technique needed for converting data between relational database records and an object-oriented programming language.

Of course, there are plenty of O/R mapping tools, but I guess that a fool with a tool… So, lets look at O/R mapping then.

As you can see in the next picture there are subtle differences between the physical database model (database diagram) and the UML model (class diagram).

OR Mapping

Aliases. Obviously there is a difference in naming. In the database there is a table called student while in code there is a class called Student. Similarly, the same holds true for their respective attributes. In the database a column is called first_name while in code it is named FirstName. Mappings needed here, however, are quite straightforward.

Type conversion. There also is the difference in data type. In the database you have something like varchar(25) or char(8) and in code it is in both cases a string. Mappings can be made, but not fully bidirectional. The problem is that in the database it has a length constraint whilst in code it has not.

Relations. In the class diagram the class Student has associations with both Mentor and Course classes. Besides the question how to represent the association, by id or collection, there is the problem of how to represent many-to-many associations. The UML model has 3 entities, while the database diagram has 4! The join table course_student is “lost” in the mapping.

In code this could be like this:

public class Student {
	public string FirstName ;
	public List<Course> Courses;
}

public class Course {
	public string CourseName ;
	public List<Student> Students;
}

public class Mentor {
	public string MentorName ;
	public List<Student> Students;
}

If you want to master the art of model-driven code generation, an essential thing you need is a model of some kind. Maybe you are in desperate need of Kate Moss, but that’s not the kind of model I talking about. I mean some kind of data model.

Preferably, you describe your model in UML. But that is not essential.

As far as I am concerned, you can write it down in notepad, if you like.

My model contains students. Students are member of a certain class, for example a class named Class 3a. A typical class consists of many students, but a student can only be part of one class. The students attend many different courses and a course can have many students.

This data model translates to database tables and relations. In this case you have a table Student, Class and Course. Student has a 1-to-many relationship with Class and a many-to-many relationship with Course.

If you created this database and then extracted a database model from the database, it would look like this:

class-student-course DBS

This would be a physical data model. A drawback of a physical model is that there is no proper way to show a many-to-many relationship. A join table StudentCourse is needed to show such a relationship. In fact it is a pattern to create a many-to-many join in a table.

In UML it looks like this:

class-student-course UML

And this is really all there is to create an UML class diagram.

With the introduction of Unity v1.2 it is now possible to do aspect oriented programming (AOP) using Unity in a way that is similar to Policy Injection. You can read all about it in my former post How-to AOP: Validation with Policy Injection, where I showed how-to AOP using Validation with the Policy Injection Application Block (PIAB).

The example of today is a rework of the previous Policy Injection example, so most code remains unchanged. Most important exercise is that the invoking code in the method Save of the facade CustomerManager is changed so – surprise, surprise – Unity does the AOP work instead of Policy Injection.

Unfortunately, out-of-the-box Unity does not have something like an ArgumentValidationException.

So, some extra code has to be written, mostly to make Unity do its AOP thing work. To stay in line with the PIAB example, some behavior of the Policy Injection ValidationCallHandler is mimiced: when validation fails, an exception is thrown.

Of course, you can reuse the ArgumentValidationException of PIAB, but then you still need PIAB. For this example, I am an Unity purist and create something myself that looks like an ArgumentValidationException, smells like an ArgumentValidationException, in fact is called an…

… EntityValidationException.

Yeah right, I gave it a different name for educational purposes so you wouldn’t think: Wow, Unity also has this powerful way of handling validation. What a great piece of work this Unity is!

Well, maybe Policy Injection will fully integrated in the next version of Unity. Maybe not.

First, you have to change the code in the method Save of CustomerManager to use Unity:

    public bool Save(Customer customer)
    {
        bool IsValid = false;

        IUnityContainer container = new UnityContainer();
        container.AddNewExtension();

        container.RegisterType().Configure().SetInterceptorFor(new InterfaceInterceptor());

        IRepository action = container.Resolve();
        try
        {
            action.Save(customer);
        }
        catch (EntityValidationException ex)
        {
            ValidationResults results = ex.ValidationResults;
            // ...
        }

        return IsValid;
    }


Essentially, this is the most important part of the exercise. As you can see, Unity uses an interception mechanism for the AOP behavior. As in the Policy Injection example, an interface is needed for registering the type. Unity has no built-in ValidationCallHandler like Policy Injection, so you have to create one yourself. This is not very difficult, see below:

 

    public interface IRepository
    {
        [EntityValidation]
        void Save(Customer customer);
    }


EntityValidation is a concrete HandlerAttribute:

 

    public class EntityValidationAttribute : HandlerAttribute
    {
        public override ICallHandler CreateHandler(IUnityContainer container)
        {
            return new EntityValidationHandler();
        }
    }

A HandlerAttribute needs to return a concrete class which implements ICallHandler:

 

public class EntityValidationHandler : ICallHandler
{
    public int Order { get; set; }
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        Customer customer = input.Arguments[0] as Customer;

        ValidationResults results = Validation.Validate(customer);

        if (results.Count == 0)
        {
            return getNext()(input, getNext);
        }
        else
        {
            throw new EntityValidationException(results);
        }
    }
}


Lastly, you need an exception to mimic the ArgumentValidationException:

    [Serializable]
    public class EntityValidationException : Exception, ISerializable
    {
        readonly private ValidationResults validationResults;

        public EntityValidationException(ValidationResults validationResults)
        {
            this.validationResults = validationResults;
        }

        protected EntityValidationException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            this.validationResults = (ValidationResults)info.GetValue("EntityValidationException.validationResults", typeof(ValidationResults));
        }

        public ValidationResults ValidationResults
        {
            get { return validationResults; }
        }

        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("EntityValidationException.validationResults", validationResults);
        }
    }


That’s most of it. Nice, huh? To be honest with you: I slightly prefer Policy Injection over Unity Interception. Why? It feels like the subtle difference Policy Injection is AOP and Unity supports AOP. It’s just a feeling.

Validation of user input is very important. A lot of our users are very environmentally aware and throw all kinds of garbage in (= garbage out). So you probably better use extensive validation for all your dataclasses (or Business Entities, if you like).  A consequence is that you have to invoke validation almost everywhere in your business logic. That’s a lot of boooooring repetitive work.

To me this smells like a cross-cutting ‘AOP’ concern, i.e. use Policy Injection.

In the following example of validation “the AOP way” I show you how to use Validation with Policy Injection, which are both part of Enterprise Library.

For simplicity we are going to validate a very simple Customer class, which still is very realistic. Even in the real world you can come across some really simple customers, like this one:

“I do not want to pay a penny extra for validation. When I buy me an application I expect that you deliver one fully validated without errors in it. So if you want validation, please do it at your own expense.”

Yes, this customer is in heavily need of managing customer expectation, but that’s a different story.

The how-to example is build around a Factory Design pattern (Customer, interface IRepository, and concrete class CustomerRepository) and accessed via Facade pattern (CustomerManager). I use a facade here, because then you do not not have to reference parts of Enterprise Library in your client code. Enterprise Library can stay within a single class library together with the other stuff. Isolation of the chosen technical implementation. In this way we can easily replace it with a better implementation, if we don’t like Policy Injection any more.

public class Customer
{
    string m_FullName;

    [StringLengthValidator(5)]
    public string FullName
    {
        get { return m_FullName; }
        set { m_FullName = value; }
    }
}

The property FullName is decorated with a validation attribute StringLengthValidator. Upon validation it is checked if the length of the string does not exceed 5. I know, silly validation.

The client code is as follows, it just calls the CustomerManager facade:

CustomerManager mgr = new CustomerManager();

Customer customer = new Customer();
customer.FullName = "thisisaverylongname";

bool IsValid = mgr.Save(customer);

The CustomerManager façade:

    public bool Save(Customer customer)
    {
        bool IsValid = false;

        IRepository ctr = PolicyInjection.Create();
        try
        {
            ctr.Save(customer);

            IsValid = true;
        }
        catch (ArgumentValidationException ex)
        {
            ValidationResults results = ex.ValidationResults;
            // ...
        }

        return IsValid;
    }

Finally, the interface IRepository and its concrete class CustomerRepository:

//IRepository interface:
interface IRepository
{
	[ValidationCallHandler]
	void Save(Customer customer);
}

class CustomerRepository : IRepository
{
	void IRepository.Save(Customer customer)
	{
		// Saving logic...
	}
}

With this concrete example at hand you should have a start of and be able to experiment a little bit with validation the AOP way.

If you need some extra help with the above example or have a strong opinion towards use of the Policy Injection, just leave a comment.

The DAO design pattern is traditionally associated with the Java Core J2EE Patterns, but this relatively simple pattern is equally applicable to our Microsoft .NET world.

This time I am not talking hypothetical here, since recently I saw it being used extensively in real world .NET webportal code I was auditing. I guess it is time to investigate this pattern in more detail.

data-access-object-pattern

A great advantage of the DAO pattern is that it separates the business logic and data access layers which – in an ideal situation – should know nothing about each other and where probably both will be changed frequently and independently. Changes of business logic can trust on the same DAO interface, while changes in persistence logic do not have any impact on its DAO clients as long as the interface is implemented correctly.

In this pattern the business object is the client which needs to get or set some data from a remote datasource. It is doing so by creating a data access object and a transfer object, which is a vehicle and contains the data.

class BusinessObject
{
    public void Run()
    {
        DataAccessObject dao = new DataAccessObject();

        //Set data
        string input = "Hello?";
        TransferObject to1 = dao.GetTransferObject();
        to1.SetProperty(input);
        dao.SetTransferObject(to1);

        //Get data
        TransferObject to2 = dao.GetTransferObject();
        string output = to2.GetProperty();

        Console.WriteLine(output);
        Console.ReadKey();
    }
} 

The data access object contains the data source and functions like an object adapter. It fills the transfer object with data.

class DataAccessObject
{
    private DataSource m_DataSource;
    public DataAccessObject()
    {
        m_DataSource = new DataSource();
    }

    public TransferObject GetTransferObject()
    {
        TransferObject data = new TransferObject();
        data.SetProperty(m_DataSource.GetData());
        return data;
    }

    public void SetTransferObject(TransferObject data)
    {
        m_DataSource.SetData(data.GetProperty());
    }
} 

The transfer object just represents the data from the data source in object format.

class TransferObject
{
    string m_Property;
    public void SetProperty(string property)
    {
        this.m_Property = string.Format("TransferObject->{0}", property);
    }
    public string GetProperty()
    {
        return m_Property;
    }
} 

Most of the times the data source will be some database, but it can be anything varying from a flat file to an ERP adapter. For the sake of this simplified example the data source is just another object.

class DataSource
{
    private string m_Data;
    public string GetData()
    {
        return m_Data;
    }

    public void SetData(string data)
    {
        m_Data = string.Format("DataSource->{0}", data);
    }
} 

The data access object design pattern is a relatively simple pattern you can use to separate you business logic from the actual implementation of the data source. The pattern is originally associated with J2EE patterns, but as I showed in the example code it also suits very well as a .NET pattern.

State pattern is intended to provide a mechanism to allow an object to alter its behavior in response to internal state changes. To the client, it appears as though th object has changed its class.

image

And last, but not least, my most favorite design pattern: the State pattern. Why it is my favourite pattern? I am not sure, but I just like the fact that you can manipulate the state of an object. Once you get the idea of states, it is a very powerful way to add behavior to an object.

All the client needs to know is about a certain context and a state, which is injected into the context. Voila, the context has a state. By calling a method Request another state is requested. Nice, huh?

class Client
{
    static void Main()
    {

        State state = new FirstConcreteState();
        Context context = new Context(state);

        Console.Write(context.State.GetType().Name + "->");

        context.Request();
        Console.Write(context.State.GetType().Name + "->");

        context.Request();
        Console.WriteLine(context.State.GetType().Name);

        Console.ReadKey();
    }
}

The abstract class State defines a method to handle the change of state within the current context.

 

abstract class State
{
    public abstract void
    Handle(Context context);
}

Upon creation of the context a state is injected and can be changed by calling a method Request.

 

class Context
{
    public Context(State state)
    {
        this.State = state;
    }

    public State State  { get; set; }

    public void Request()
    {
        this.State.Handle(this);
    }
}

The concrete states implement how the change of state is handled.

 

class FirstConcreteState : State
{
    public override void Handle(Context context)
    {
        context.State = new SecondConcreteState();
    }
}

class SecondConcreteState : State
{
    public override void Handle(Context context)
    {
        context.State = new FirstConcreteState();
    }
}

I think this is a nice pattern. You can apply this pattern in many ways, for example simple workflow or wizard like pages. One example I like is that of a dataform. When it shows up there is no need to save data, since it not has been altered. As soon as data is filled in the state of the form changes and the save button is enabled.

 

This post is part of a series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern by looking at a minimalistic example to reveal its structure and then look at more concrete and useful real-world C# code that implements the pattern.

The Strategy pattern is intended to provide you with a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable.

image

This is one of my favorite design patterns, because it provides you a way to encapsulate a strategy. This comes in very handy when you suspect that there will be a strategy update in the near future. For example, you could use this pattern for report engine selection.

The client first creates a context, in which a strategy is injected. In this simplified example a result is returned by a method called ContextInterface. Independent of the strategy selected, invocation of the method and collecting its result remains the same.

class MainApp
{
    static void Main()
    {
        Context context;
        Strategy strategy = new FirstConcreteStrategy();
        context = new Context(strategy);
        string result = context.ContextInterface();
        Console.WriteLine(result);

        strategy = new SecondConcreteStrategy();
        context = new Context(strategy);
        result = context.ContextInterface();
        Console.WriteLine(result);

        Console.ReadKey();

    }
}

An abstract class Strategy defines an algorithm interface as a method.

abstract class Strategy
{
    public abstract string AlgorithmInterface();

}

The concrete classes implement the abstract method.

class FirstConcreteStrategy : Strategy
{
    public override string AlgorithmInterface()
    {
        return "FirstConcreteStrategy";

    }
}

class SecondConcreteStrategy : Strategy
{
    public override string AlgorithmInterface()
    {
        return "SecondConcreteStrategy";
     }
}

The Context class contains a strategy, which is injected upon instantiation. The public method ContextInterface provide a way to call the algorithm interface of the encapsulated strategy.

class Context
{
    private Strategy m_Strategy;
    public Context(Strategy strategy)
    {
        this.m_Strategy = strategy;
    }
    public string ContextInterface()
    {
        return m_Strategy.AlgorithmInterface();
    }
}

You see? It is a relatively simple pattern and similar to the factory method pattern. In my humble opinion there is not much difference between them.

This post is part of a series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern by looking at a minimalistic example to reveal its structure and then look at more concrete and useful real-world C# code that implements the pattern.

The Prototype pattern is a simple pattern intended to provide you with a way to dynamically select which object to instantiate, and to return a clone of a prototypical object.

image

This is a relatively simple pattern. You create a prototypic reusable object and use it as a base for other objects. This pattern comes in handy when recreating the new object is time consuming and they differ only a little from the prototypic object and each other.

class Client
{
    static void Main()
    {
        ConcretePrototype original = new ConcretePrototype();
        original.Data = "original";
        Console.WriteLine("Original: {0}", original.Data);

       // Do the cloning
       ConcretePrototype clone = (ConcretePrototype)original.Clone();
       Console.WriteLine("Cloned : {0}", clone.Data);

      // Is it really a clone?
      clone.Data = "clone";
      Console.WriteLine("Cloned : {0}", clone.Data);
      Console.WriteLine("Original: {0}", original.Data);

      Console.ReadKey();
   }
}

The base class prototype contains some data and a method for cloning.

abstract class Prototype
{
    private string m_Data;
    public string Data
    {
        get { return m_Data; }
        set { m_Data = value; }
     }

     public Prototype()
     {
     }

      public abstract Prototype Clone();
}

The concrete class implements the cloning stuff, which in .NET is very easy by virtue of the built-in method MemberwiseClone, which creates a new object and then copies the nonstatic fields of the current object to the new object.

class ConcretePrototype : Prototype
{
    public override Prototype Clone()
    {
        return (Prototype)this.MemberwiseClone();

    }
}

The prototype pattern can come in handy when you need cloning. I have used this pattern heavily in my – soon to be – famous Silverlight game WORM. If you like, I can show you in a next post. Let me know.

This post is part of a series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern by looking at a minimalistic example to reveal its structure and then look at more concrete and useful real-world C# code that implements the pattern.

Pages: Prev 1 2 3 4 5 6 7 Next