Category Archives: Enterprise architecture

A follow-up on my unlikely Doomsday Scenario for SQL Server On Premises

A few days ago I published a post that conjectured about a rather unlikely scenario regarding SQL Server On Premises.

I was basing my conjecture on one single fact: that native client connectivity to SQL Server On Premises through SNAC is no longer supported, and that from now on, the only supported way to connect from client apps will be through an expanded ODBC driver.

Between August and September 2016, the Microsoft SQLNCli team blog published the following posts:

ODBC Driver 13.1 for SQL Server Released

Preview Release of the SQL Server [C/C++] ODBC Driver 13 for Linux

These two posts open the door to a different kind of scenario:

SQL Server has become a multi-platform technology, and it makes more sense for the team in charge of connectitivy tools to offer the best tools for all platforms, but at the same time, this team has to strive for as much maintainability for these tools as it is possible. One way to achieve that is to look for an API that can connect to all platforms, and that clearly is ODBC.
The SQLNCli team is working on the double to include in these ODBC drivers support for all relevant technologies previously available through SNAC and OleDb.

Kind regards, GEN

Advertisements

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

What is software architecture? What does a software architect do? How could we tell the good software architects from the bad software architects?

LightSpeed

In this post I will deal with an interesting (and thorny) set of questions regarding architecture.

Without much further ado, let’s get into the game.

What is software architecture?

In a broad sense, software architecture is the complete set of design decisions that defines and determines the structure of a given software solution, but let’s bear in mind that when we talk about “software architecture“, we really mean the main design decisions that define the main structural elements of a given software solution, and not each and every design decision, that may include a large amount of rather simple, obvious and very uninteresting design decisions.

What does a software architect do?

In plain and simple terms, the software architect is the person that makes those design decisions, so, that is mainly what the software architect does:
making the design decisions regarding a given software solution.

How could we tell the good software architects from the bad software architects?

To be able to answer this question, we should start with a simpler question:

How could we tell a good design decision from a bad design decision?

Well, design decisions are either good or bad just because of their consequences: a design decision is good if and only if it produces good consequences, just as much as it will be bad if and only if it produces bad consequences.

So, getting back to the answer for the original question, the good software architects are the ones that make design decisions that have good consequences for the project, the team and the product, and the bad software architects are the ones that make design decisions that have bad consequences for the project, the team and the product.

I am aware of the fact that any Product Owner may argue that my answer is not useful for them since, by the time they realize that the software architect is not any good, it is already too late!

Well, allow to say in my defense that it is not so, since you can detect the tell-tale signs of either good or bad consequences from design decisions being made by the architect early on the duration of any software development project.

As a parting idea to this post, I will give you another tip on good software architects. All of them are really good at these two things:

1) Good software architects, when they have to make a design decision, they never forget to ask the following question:

How could I make sure that the design decision that I’m about to make will neither compromise nor limit our ability to keep making the design decision that we need, for the forseeable future?

(Since you have allowed me a few things, allow me to say that this is a quote of my own batch)

2) Good software architects, when they ask themselves this question, they always figure out a successful answer to it for the solution at hand.

Most people may argue that the question in 1) is an impossible question since we cannot predict the future, so, there is no way that today we could guess what might be the design decisions that we will need to make in the future.

Again, allow me to say in my defense that most people are not software architects (let alone good software architects), so, most people will not pay attention to the key to this question: “neither compromise nor limit our ability to keep making the design decision that we need

Good software architects do not need to predict the future to be able to figure out the answer to the key to the question.

Kind regards, GEN