Tag Archives: Agile

An Investigation on Database Id Generation Strategies (Part I)

The World ID-10092667

In this post, I will Investigate how Id generation strategies chosen for primary keys of business entities at the database level may impact the entire solution. Databases that are the repository of a transactional application do not work in a vaccum: They are a part of a larger solution.

So, design decisions for the database should not be made away from the context of the design decisions of the entire solution. On the contrary, all main design decisions regarding the database of any transactional application should be made considering the impact they may have on the solution as a whole.

So, proper trade-offs may apply regarding all main design decisions in a database that is the repository of a transactional application, including Id Generation Strategies for all business entities that are persisted by the application in the database.

Regarding the architecture of any given solution, we could say that it is all about the design decisions that we make and the consequences of such decisions.

Proper trade-offs are those that could strike the best possible balance of the consequences (both positive and negative) that may impact the solution in the short, mid and long term.

To conduct this investigation, I will choose an Ad-Hoc approach:
I will first navigate the problem, so we all could grasp a better understanding of what is at stake when we make isolated design decisions regarding Id Generation Strategies.

Once we have navigated the problem, so that we have some good understanding of the pros &cons of such a way of making design decisions, we will be in a much better position to explore possible solutions to this problem.

We could not argue that we fully understand any given solution if we do not have a deep understanding of the problem that such a solution is meant to solve.

Since my interest is to investigate this general problem from an architectural perspective, I  will use common design patterns and tools, like Separation of Concerns, Model-View-Mediator (this is a generic way to refer to patterns like Model-View-Controller or MVC, Model-View-Presenter or MVP, or Model-View-ViewModel or MVVM) and Object Relational Mapping (ORM).

When I say “MVC” I mean any tool that implements the MVC form of the general Model-View-Mediator pattern, and not just ASP.NET MVC, as it just as well applies to Spring.NET, or to any other MVC-based tool.

Why should we care to use these patterns and tools?

Mainly, because they are useful to us in a very practical way: they allow us to achieve our development goals with the least amount of effort from our part, if we make proper use of them.

The principle of Separation of Concerns is a very pervasive principle in Software Architecture, since it is applied in just about any architectural tool that we could consider, like for instance, when we use any Model-View-Mediator based tool, or when we use any ORM tool.

The principle of Separation of Concerns (SoC) states that we will organize our code in chunks in such a way that any given chunk of code will have a single and well-defined purpose, and it does not assume any superfluous responsibilities.

It means that if we choose to have an n-tier (or multiple layer) architecture, one of the main reasons behind this decision is the SoC principle.

It also means that if we choose to use some kind of Model-View-Mediator approach (like say, MVC, or MVVM, or MVP), one of the main reasons behind this decision is the SoC principle.

It would also mean that if we choose to use an ORM tool (like say, NHibernate, or EF), one of the main reasons behind this decision is the SoC principle.

With any of these tools and patterns, we use the concept of Model.

The Model is a software representation of a solution to a known problem.

The Model includes all the entities or business objects that are required by the solution to solve such a known problem.

Following the SoC principle, some chunk of code at some layer or tier will use these entities to apply the necessary logic that solves the business problem at hand.

By the same token, some other chunk of code at some other layer or tier will use these entities to persist their changes of state at the proper time and at the proper data repository.

The focus of my investigation will be at the level of this particular responsibility: how the different database id generation strategies affect the CRUD operations of business objects, and I will use an ORM tool as a helper for my analysis.

Speaking of ORM tools: why do we use them? what kind of problem do they solve for us?

As I have already said, the Model is a software representation of a solution to a known problem.

If we use an object-oriented representation of a given solution, such representation is aptly named the Object Model (OM) of said solution.

If we use an entity-relationship representation of a given solution, such representation is aptly named the Data Model (DM) of said solution.

For any given solution, its Object Model is very different from its Data Model.

If your team has to implement a solution with an OOP language like C# and a database like MS-SQL Server, such difference between the two representations of the solution poses a very serious problem to the software development effort of your team.

The formal name for this problem (the wide gap between the OM and the DM of a given solution) is Object-Relational Impedance Mismatch (ORIM).

It has been proven that a certain set of patterns is effective in the solution of the ORIM problem.

ORM tools are practical implementations of these patterns.

All ORM tools use a technique known as Mapping to bridge the gap of the ORIM problem.

ORM tools allow us to use a default set of Mapping rules and conventions, and they also allow us to customize the rules and conventions to be used by our implementation.

The simplest way to use any ORM tool is with the default set of Mapping rules and conventions.

In this post I will use NHibernate as a reference model for an ORM tool.

I will present and use concepts that are relevant for any given mainstream ORM tool, but I will use the names of those concepts as they are referred by NHibernate.

I will start with the simplest of examples, and I will gradually move on to more complex examples.

Since I want to explore how the different database id generation strategies may affect the CRUD operations of business objects, in my first example I will let the ORM tool choose the database id generation strategy by letting it use its default behaviour, then do some basic CRUD operations and use the debugging tools from the ORM engine to obtain useful information to analyze how good (or bad) is the default Id generation strategy from the perspective of the system as a whole.

To do this, I have chosen to use the approach commonly known as “Code First”, and let the ORM tool generate the database schema source code for the Model used in my first example.

I will use some POCO classes as the entities of my Model.

But before I go on, it would be useful to explore a little deeper into the Model and how it is used by the different layers or tiers.

When it comes to solving a given kind of problem, it is at the level of the Business Logic Layer where the “actual” solving of the problem happens.

When it comes to persisting and retrieving the state of business objects, it is at the level of the Data Access Layer where those kinds of operations happen.

At the level of the Business Logic Layer (BLL), all business objects (instances) of all business entities (entity classes) participate.

At the level of the Data Access Layer (DAL), only instances of persistent business entities (persistent entity classes) participate.

For many kinds of businesses, there is a subset of business entities that are non-persistent: that is, instances of such non-persistent entity classes are required and used at the BLL level, but none of such instances of such classes exist at the DAL level, which means that the database schema has no tables to represent the non-persistent entity classes.

At this point, it is very useful to present an example of such kind of scenario.

Let’s consider the following business example: A company has an customer loyalty program as part of their CRM business processes.

Some of the business processes involved in the customer loyalty program apply certain business rules based on algorithms that calculate metrics as a function of the “age” of a given customer in the customer loyalty program.

Let’s suppose that, for any given order, there are 10 different algorithms that use this “age” of the customer to calculate these metrics.

The “age” of a given customer in the customer loyalty program is the number of days, expressed in years (as a real number) between the start date when such a customer joined the program, and today’s date.

We should all realize  that the start date when any given customer joins the customer loyalty program has to be a public property of some business entity that has to be a persistent entity class.

The “age” of a customer in the program, as a property, it is a function of the start date and today’s date, so, it is not an independent property, so, it should not be persisted.

Regarding the aforementioned algorithms (we have supposed that there are 10 different calculations for each new order), we could just as well use the persistent start date as parameter with each one of them. But if we did so, it would mean that for each order, we would have to calculate the very same subtraction ten times in a row, which is a clear waste of resources.

So, why not use some non-persistent business entities at the Business Logic Layer when it seems to be useful and it makes a lot of sense from many perspectives?

Now that we have gone through the rationale behind non-persistent business entities, let’s delve into a simple Object Model that could solve the “Tango with Persistent & Non-Persistent classes”:

EntityHierarchy

Now, we can get back to the simplest way to use the “Code First” approach so that our choice of ORM tool, using defaults, generates the source code for the database schema of our Model.As we are using NHibernate as a reference model for any ORM tool, the simplest way to achieve what we need is with Automapping. What Automapping really means is that we will use the default set of rules and conventions with very little customizing.

With Automapping we can tell our ORM tool to generate the source code of the database schema that corresponds to our Model, that is, the object model that represents the business entities of the domain of our solution.

Since the domain of our solution is comprised of two subsets, a subset of persistent business entities, and a subset of non-persistent business entities, we need to tell our ORM tool to generate a database schema that only includes the persistent business entities.

The code for the base classes that we need to solve the “Tango” are these:

namespace SimpleAutoMap.Domain
{

public abstract class EntityBase
{}

}

namespace SimpleAutoMap.Domain
{

public abstract class NonPersistentEntityBase : EntityBase
{}

}

namespace SimpleAutoMap.Domain
{
public abstract class PersistentEntityBase : EntityBase
{
public virtual int Id { get; set; }
}

}

It is interesting to note that, in our model, the base class for all persistent business entity classes already has the Id property included: in this case, we are using implementation inheritance so as to save code!
It is also very important to note that so far, we have only dealt with the “Tango” of Persistent and Non-Persistent classes strictly from the perspective of pure implementation inheritance, and we still need to do some more work so that our ORM tool will work with the business entities as we expect it to do.
Now that we have our base classes in place, we can move on to the main classes of our (rather simple) model:
namespace SimpleAutoMap.Domain
{
public class Product : PersistentEntityBase
{
public virtual string ProductName { get; set; }
}

}

namespace SimpleAutoMap.Domain
{
public class Customer : PersistentEntityBase
{
public virtual string CustomerName { get; set; }
public virtual DateTime InceptionDate { get; set; }
public virtual DateTime ClpStartDate { get; set; }
}

}

namespace SimpleAutoMap.Domain
{
public class LineItem : PersistentEntityBase
{
public virtual int Quantity { get; set; }
public virtual decimal UnitPrice { get; set; }
public virtual Product Product { get; set; }
}

}

namespace SimpleAutoMap.Domain
{
public class Order : PersistentEntityBase
{
public virtual DateTime OrderDate { get; set; }
public virtual Customer Customer { get; set; }
public virtual IList LineItems { get; set; }
}

}

namespace SimpleAutoMap.Domain
{
class ClpProcessingOptions : NonPersistentEntityBase
{
public double Age { get; set; }
}

}

(NOTE: in the original post, I forgot to include the properties InceptionDate and ClpStartDate to Customer. Now it is fixed!)

Before we go any further, it would be very useful to say a word about why all the properties of the persistent entities have the modifier virtual, while at the same time, the properties of the non-persistent entities do not have the modifier virtual?

At this point I do not want to distract the attention away from the main goal of this post, but nonetheless I will give a short but proper answer to this valid and important question.

From the perspective of the engine of any ORM tool, the model is an atomic unit, in the sense that each and every entity class that is a part of the persistent subset of the model (the part of the model that is relevant to the ORM engine) is “created equal”.

Unless we say otherwise, when we tell the ORM engine to “load”, it will try to load to memory each and every instance of each and every entity class (which happens to be a real waste of resources!).

This funny way to behave (the default behaviour) is apty named eager loading. But if any ORM tool would only support eager loading, it would be useless to us.

So, in order to be useful, all ORM tools also support another behaviour, apty named lazy loading.

With lazy loading, we have complete programmatic control over when and how any give set of instances of any given entity class is loaded to memory by the ORM engine.

To be able to support lazy loading, all entity classes (so as to be able to be handled by the ORM tool in this way), MUST have all of its public properties declared as virtual.

Well, now that we can get back to own main interest, we have to figure out a way to tell the ORM engine to include into the Data Model only the entity classes that inherit from the class PersistentEntityBase.

With NHibernate this goal is very simple to achieve: the default set of rules and conventions is controlled by the class DefaultAutomappingConfiguration.

All we have to do is create a subclass of DefaultAutomappingConfiguration with the proper behaviour and use it in our implementation.

The class DefaultAutomappingConfiguration has a very useful method that will help us in what we want to achieve: the method ShouldMap.

The overload of this method that is interesting to our investigation has the following signature:

public virtual bool ShouldMap(Type type)
This overload in particular is very useful, indeed, for it is virtual (which means that we can override it with our own specialized logic), and it receives as parameter any object of the class Type.
This is simple and wonderful at the same time, as we can figure out how the ORM engine uses this overload: it iterates over the entire set of entity classes of the model, and for each given entity class, it passes it to this method and uses its outcome to determine if said entity class of the model has to be mapped or not.
This is exactly what we need to tell the ORM engine to map only those entity classes that inherit from the base class PersistentEntityBase.
So, our subclass of the base class  DefaultAutomappingConfiguration looks like this:
namespace SimpleAutoMapping
{

public class SimpleAutoMappingConfiguration
: DefaultAutomappingConfiguration
{
public override bool ShouldMap(Type type)
{
return type.IsSubclassOf(typeof(PersistentEntityBase));
}
}

}

Finally, we are ready to tell our ORM tool to follow its default behaviour (with just a very simple customizing), and generate the database schema for the subset of the persistent entity classes of our model.

With a powerful ORM tool (like for instance, NHibernate!), we need a very simple routine to do this:

class Program
{

static void Main(string[] args)
{
string outputFileName = ConfigurationManager.AppSettings[“OutputFileName”];
var cfg = new SimpleAutoMapConfiguration();var configuration = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008)
.Mappings(m => m.AutoMappings.Add(
AutoMap.AssemblyOf<Customer>(cfg)))
.BuildConfiguration();
var exporter = new SchemaExport(configuration);
exporter.SetOutputFile(outputFileName);exporter.Execute(false, false, false);
Console.WriteLine(“\n\nDB schema source code.”);
Console.ReadLine();
}

}

This routine generates a database schema that looks like this:

if exists (select 1 from sys.objects where object_id = OBJECT_ID(N'[FKDDD0206ACBEF7F6]’) AND parent_object_id = OBJECT_ID(‘[LineItem]’))
alter table [LineItem] drop constraint FKDDD0206ACBEF7F6

if exists (select 1 from sys.objects where object_id = OBJECT_ID(N'[FKDDD0206A75BA3E60]’) AND parent_object_id = OBJECT_ID(‘[LineItem]’))
alter table [LineItem] drop constraint FKDDD0206A75BA3E60

if exists (select 1 from sys.objects where object_id = OBJECT_ID(N'[FK3117099B4095694A]’) AND parent_object_id = OBJECT_ID(‘[Order]’))
alter table [Order] drop constraint FK3117099B4095694A

if exists (select * from dbo.sysobjects where id = object_id(N'[Customer]’) and OBJECTPROPERTY(id, N’IsUserTable’) = 1) drop table [Customer]

if exists (select * from dbo.sysobjects where id = object_id(N'[LineItem]’) and OBJECTPROPERTY(id, N’IsUserTable’) = 1) drop table [LineItem]

if exists (select * from dbo.sysobjects where id = object_id(N'[Order]’) and OBJECTPROPERTY(id, N’IsUserTable’) = 1) drop table [Order]

if exists (select * from dbo.sysobjects where id = object_id(N'[Product]’) and OBJECTPROPERTY(id, N’IsUserTable’) = 1) drop table [Product]

create table [Customer] (
Id INT IDENTITY NOT NULL,
CustomerName NVARCHAR(255) null,
InceptionDate DATETIME null,
ClpStartDate DATETIME null,
primary key (Id)
)

create table [LineItem] (
Id INT IDENTITY NOT NULL,
Quantity INT null,
UnitPrice DECIMAL(19,5) null,
Product_id INT null,
Order_id INT null,
primary key (Id)
)

create table [Order] (
Id INT IDENTITY NOT NULL,
OrderDate DATETIME null,
Customer_id INT null,
primary key (Id)
)

create table [Product] (
Id INT IDENTITY NOT NULL,
ProductName NVARCHAR(255) null,
primary key (Id)
)

alter table [LineItem]
add constraint FKDDD0206ACBEF7F6
foreign key (Product_id)
references [Product]

alter table [LineItem]
add constraint FKDDD0206A75BA3E60
foreign key (Order_id)
references [Order]

alter table [Order]
add constraint FK3117099B4095694A
foreign key (Customer_id)
references [Customer]

We can check that the ORM tool, with the small set of constraints that we have given it and its own default behaviour, has generated a database schema that uses IDENTITY-based primary keys on all entities.

How good (or bad) is this decision from the perspective of the entire solution (and not just from the perspective of the database itself)?
We will explore this in my next blog post (Part II of this investigation).

To download the code sample, click here

Kind regards, GEN

Globalization and some challenges Agile teams are facing

Image

When it comes to the IT industry, some of the more important consequences of Globalization are Outsourcing of IT operations and Outsourcing of many software development posts.

Regarding the Outsourcing of software development posts, in general this has turned out to be a positive move for software companies and IT professionals in developing countries, as they have experienced a growth in their business operations driven by this process.

But this movement also has brought its own share of ills into the mix.

Now, the typical software development project has a team with team members from many countries, working across many time zones. The most frequent process used by these teams is Agile.

Let’s review some of the challenges that these Agile teams are facing, in no particular order.

One of such challenges is the diverse cultural backgrounds of team members. Even though diversity in general, and diverse cultural background in particular, is a very positive factor for an Agile team, the challenge that most frequently shows up is pertaining to communication.

One on one conversations between team members are a major aspect of Agile as a process, and diverse cultural backgrounds, including diverse native languages, pose some important issues and obstacles to the natural flow of the conversation.

[New comment added] It would make sense to expand this idea a little bit: outsourced team members in general do not belong to the same organization as the rest of the team, so, it is very likely that outsourced team members (developers) might not know the details of the business of the customer, or the meaning of business terms used by the customer when describing functional requirements and business rules (this relates to the concept of “ubiquitous language” in Domain Driven Development).

Besides this, different cultures usually have different cosmovisions, that is, different mappings to the concepts and ideas that explain the universe all around us. One of the first mappings that each person incorporates is their mother tongue, so, different native languages is an important element of the diverse ways of understanding the universe all around us. [New comment added]

But diverse cultural backgrounds is not the only challenge to one on one conversations, as all of these teams have non-collocated team members, and  that also poses a major obstacle to the flow of the conversation, at least to some of the conversations that are required to happen on a daily basis.

Another challenge is caused by the fact that team members that represent The Voice of the Customer are usually on a different “shore” from outsourced team members, most of them being developers, so, “up-close” conversations between developers and users also face some obstacles to be solved.

Another pattern that also is becoming important is that outsourced team members are also non-collocated among them, that is, outsourced team members from different regions of a country or from different countries of the world.

This pattern in particular is a major obstacle to Agile. This pattern affects many Agile practices, like one on one conversations, or even pair programming.

Another pattern that is becoming important is that all these constraints that affect these Agile teams introduce certain types of discontinuities to the process that induce issues and problems to the scalability of the team.

For instance, these constraints and discontinuities have to be mitigated with many calls and meetings of the leadership of the project, which means that team leaders are busy each and every day during a significant percentage of their available time, which means that they are not as available to team members as it would be recommended.

The principles of Agile are such that if Agile needs any fixing, it should be done from within, that is, by the team. So, in a coming post, we will discuss some solutions to these challenges.

Kind regards, GEN