Friday, April 10, 2009

Building quality and bug free software : Leverage Design By Contract

Since inception, the advent of Object orientation development gave birth to chains of concepts in recent years, and all these had positive impacts on the ways we develop robust, reliable and scalable systems that passes the test of time. One of this concept is designing software component and allowing components interaction based on contracts. These contracts are the full agreements that each components must satisfy before the system can run successfully.

A simple analogy is smashing a bottle on the floor, what do we expect? of course, we'd expect the bottle to break, and scattered all over the floor. The fact that the action smashing a bottle on the floor requires a bottle (Pre-conditions) and bottle must scatter on the floor (Post- condition). The pre-conditions and post-conditions are the contract agreement in our analogy. Now lets dig into what really is design by contract:

What is Design By Contract (DBC)

Design by contract is the ability of software components to satisfy obligations that are required for the smooth running of a software systems. Was introduced into the Eiffel programming language designed by Bertrand Meyer in 1988.


Now, the word design by contract is used to associate software contracts/specifications with the software development itself, by so doing, we described what the software component expects from calling component or client. This approach makes the development of software and its specification to be interwoven and changed when either changes.

Again What is Design By Contract

Design by contract is a software development standards that enforces a pre-conditions and post-conditions on the ways software components/ methods and libraries communicate with one another. An object oriented class should depict what it represents. If you have a class called AccountValidator, the job of that class is to validate an Account not to withdraw from that account, another class or service will handle the withdraw aspect.

To validate an account, we will Require an Account Details object, and the algorithms for validating an account, and also Ensure that the account is valid, and there is no invalid data supplied. Note the two words Require and Ensure , these are analougous to the pre-conditions and post-conditions that we have been refering to. So if you are developing the AccountValidator class, the methods should require that parameters meets its demand and ensure that valid validation response is sent to the consumer.

Why all this, what about TDD (Test Driven Development)

Yeap, TDD allows you to pre-verify your code against certain conditions too. And if you have been using Assert statements to verify outputs from your test, you are near design by contract. But DBC allows you to have the assertions into your code not outside your code. Your methods should be strict enough and only bound to its part of the contract.

All talk and no code : Tell me more

Now lets consider the following class AccountValidator, and its contract obligations :


interface IAccountValidator
{
bool ValidateAccount(IAccountDetails account);
}


//IAccountValidator Implementation

public class AccountValidator : IAccountValidator
{
public bool ValidateAccount(IAccountDetails account)
{
if (ValidateAccountNumber(account.AccountNumber))
{
if (ValidateNameOnAccount(account.NameOfAccount))
{
//Now ensure that the value is in the database

if(ValueIsInDataBase(account))
return true;
}
}

return false;
}

private bool ValidateAccountNumber(string accountNumber)
{
if (string.IsNullOrEmpty(accountNumber))
throw new InvalidOperationException("Invalid Account Number");

if (accountNumber.Length != 8)
throw new InvalidOperationException("Account number must be exactly 8 characters long");

return true;
}

private bool ValidateNameOnAccount(string name)
{
if (string.IsNullOrEmpty(name))
throw new InvalidOperationException("Invalid Account Name");

return true;
}

private bool ValueIsInDataBase(IAccountDetails account)
{
//Database calls here
}
}




The class above specifies to pre-conditions, these are valid account number and valid account name. The post-conditions of this class would have been checking that the actual data submitted is valid in the database. This class is just a simple and classic design by contract example, more advanced frameworks has been produced using aspect weaving or aspect oriented programming to solve the contract issues.

DBC is comming in .NET 4.0

Code contracts will be part of the Rosairo project (VS 2010). This will allow you to have the ability of static time checking of contract violations, API documentation, improve your testability.

Sunday, March 29, 2009

Democratizing Software Development (A Promise from Rosairo) .NET 4.0

Microsoft is making a big change in its .NET suites of technologies. The Visual studio development environment will experience additional functionalities that will make life a sweet one for all of us. An application server code named "Dublin" will be introduced to compliment IIS (Internet Information Service) . WF and WCF will experience another quantum changes, and we will all be happy.

The .NET framework is not left behind, as we will see more API changes like : dynamic (supports for COM interop and dynamic languages), Named parameters, default parameters, BigIntegers, covariance and contra variance of generic list : as IList string will now be equals to IList object , also Code contracts.


Democratizing Software Development Life Cycle

There is now a big quantum leap from programming focused development environment to software life cycle development environment.

In an Agile driven development environment, the key practices there is collaboration, software developers needs to collaborate with architects, testers, project managers and database administrators. This collaborative means ensures that products are delivered on time and risks are noted on time. The collaboration amongst team of professionals already in an agile environment leveraging the .NET platform will be a plus when the new Visual Studio 2010 finally ships.

Use case, activity, architectural diagrams are other integrated features of Rosairo, developers, architects will enjoy new ways of architectural designs because all of this forms parts of the new change in VS 2010.

Ever thought about using test data to validate the efficacy of software solution. There is an added test tool that will ensure a proper scenario based documentation which is useful to application testers.

Black box testing recorder will be integrated into the Visual studio 2010, where testers can interrogate the call stack and record debug sessions for replay later. This gives the developers to watch the replay of the black box when a bug is found.

Let us fold our arms and experience the new changes to the developers number ones platform. Derio to Microsoft, Visual Studio Bomayee!!!

Tuesday, March 24, 2009

Time for BDD (Behavioural Driven Development)

A deep thought over why software project really fails or was built without actual concentration on the business cases will lead to the fact that the actual requirement was not being captured well, no feasibility study of any kind was taken to check the efficacy of the business case. We understand that Business Analyst, Quality Assurance and of course developers need a collaborative efforts to building software. Do we as developer really test first before writing the code. The test first approach makes for understandability of business requirements from coding and it makes us concentrate on what our requirements really are.

How YAGNI (You Aren't Gonna Need It) can help developers

YAGNI can help us to focus on our development needs, it will allow us to focus on the business/technical cases and reduces large complicated code referred to as code bloat. You really aint gonna need that sophisticated features if its just not helping the software requirements at the moment. I know we developers likes to write the best standardize code that meets with the current practices in our industry, that's cool but are we conscious of the time spent on the sophistication, do we put in mind that business requirements comes first before satisfying our hunger for fine grained development practices.


BDD complements TDD
The current methodologies in software houses is the Agile Methodology, whether it is being practiced in a full fledged manner or it is being tailored against your organization requirements, Agile methodologies favors incremental development over classic water fall approach. Agile methodology was referred to as cowboy coding because of its minimal planning approach, but it has proven to be successful in today's deliverable focused environments.

Agile methodologies encourages Test driven Development which in turn allows us as a programmer/developer/architect to focus more on testability of our code. At a point during the writing of large and complex systems, we loose our confidence in our code if we do not have an automated testing framework that gives us the confidence and boost our moral.

That said and done what is BDD?

Have you ever written a complex system with several many business scenarios. The reasons why systems fails is that we do not fully test all different scenarios that the system can find it self. An agile test driven developer should understand that testing scenarios goes beyond your test and mock passed, but its that your code/system meets the full capabilities and conform to clients needs.

It promotes common domain language between what the business analysts, quality assurance and the developers understand. Developers can save the technical detail when interacting with none technical people. This will enable everyone speaking the same language and everyone having common understand of the business case and where we are at.

A simple non BDD interactions

Business Manager : I want the new software to support staff tracking
Systems Analyst : It will results to us obtaining a tracking GPRS systems and API built around it.

Developers : We need to use a wrapper or/and abstraction, that will be make us not tight with third party tools. Yes it seems there is already a bluethoot API in the corner.

Business Manager : The goal of the system is to allow us know the time which the staff logs onto the systems, the idle time of the keyboard, and internet usage.

Systems Analyst : Ok i see, the provide us with your initial thougths and we can write a behavioural code that will clearify your thoughts.

The interaction above is just an example our understandibility is a neccessity in software development. You will not blame us developers for having a higher level mindsets its our job but we need to understand the business case, in other words we have to interrogate our code and simulate the business cases to get the clearer picture.

Note even the business managers do not know what they fully want, but the BDD will document and give a clearer picture of what the system should do.

Hence we need a user story

Recently i migrated a very complex business scenarios from code into WWF (Windows Workflow Foundation) . This would not have been possible if i do not know the user story. Although, i have to admit that i delt with a document which does not clearly structure the requirements in other of user stories or scenarios, all the same i picked up my own pen, and i wrote an interesting user stories from such document. Here is a simple example :

As a user of the online banking system
I want to loging with with my secure credentials
Then check my account details to see my balance record.

With This scenario, => check my account details
Given , the logging page is active and ready to take my details
And, suplying my real encrypted password
And, my real user name
when, i log in my details
Then, i was redirected to a new bank customer account page
And, I checked my account details.


If systems developers can write out a story out of the big and large software requirements documents, then the remaining code will be less painless because you would not be coding and asking about the story because you already know that the story line is happily ever after.

Watch out for when i display my experience with various BDD frameworks like Nbehave, Dan Norths Blog site, at http://dannorth.net/whats-in-a-story.

Friday, March 20, 2009

Simple dependency Injector class

It is apparent in todays application development that complexity starts from when we typed the first line of code. Code complexity is one of the code horrors mutilating todays application development. To ensure that we work around these developments show stoppers, many design patterns and software development standards have been built to help come over this poor development approach.

Today we develop software with components in mind, we develop so that we can easily decouple our systems and make it a pluggable system.

Systems are very difficult to decouple when we do not use a strategic and standardized ways of separating component concerns. Over the years, the development and Object Oriented community have realized that there was a need to separate application concerns because of changing business cases and requirements.

As a software developer i have made it a culture to think of software as several functional modules that are independent from one and other but dependent on one and other via a plugable means.

The following code shows an example of code coupling :


public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

Person person = new Person();


There is nothing wrong with the code above really for a simple application. But for a very complex application, we tend to tight couple the Person class with the calling application. Let us assume the person class was imported from a web service proxy, that means our application is relying on the web service proxy for the Person Implementation. What then happens when we are not interested in web service proxy again but in another .dll that has its own Person implementation but with some extra fields and properties, do we start to refactor our code to comply with the new Person class? I bet that is not the easiest way ever.

Let us assume that person class now implements an interface IPerson. The following code depicts the kind of defination :


interface IPerson
{
string FirstName { get; set; }
string LastName { get; set; }
}

public class Person : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
}


Hmm, now that person have implemented an interface IPerson, then we could refer to IPerson all over our code, this is fairly decoupled until the very point where we really initialised the Person class, like the following :



IPerson person = new Person();

person.FirstName = "Ahmed";
person.LastName = "Salako";


now although we ahve succesfully initialised the Person class and because it implements the IPerson interface, we can assign it to the IPerson interface. Our code is still exposed to the point where we did new Person.


A simple Dependency Injector class

The following class will serve as a repository that knows about dependencies of our application :



public static class ModelFactory
{
private static IDictionary <Type, Type> repos = new Dictionary <Type, Type>();

static ModelFactory()
{
repos.Add(typeof(IPerson), typeof(Person));
}

public static T CreateInstance < T>()
{
Type value = repos[typeof(T)] as Type;
return (T)Activator.CreateInstance(value);
}

public static T AsInterface < T>(Type type)
{
Type value = repos.Where(t => t.Value == type).FirstOrDefault().Key;

return (T)Activator.CreateInstance(value);
}
}


So with the class above, we have successfully created a dependency repository class that knows about an interface and its implementations. Here is how to use the simple dependency repository class :



IPerson person = ModelFactory.CreateInstance < IPerson>();
person.FirstName = "Ahmed";
person.LastName = "Salako";



This leaves us very happy and with code decoupling.

Tuesday, January 6, 2009

LINQ And Interpreter Pattern : A tale of datasources

In a service oriented (SOA) environment, larger systems communicate/handshake with one and other with different varieties of data and formats.

These systems leverage different Data formats, contracts and pure XML (The RESTFULL way) hosted in a multi - platform environment.

Recently, in the real life, i came across a situation that i needed to fetch information from different data sources. The consuming application(s) does not want to know where these data's are being imported from and the producing application does not want to let go of the secret of the source to data. All it is concerned about is that the format must be consistent wherever it may be coming from.

I am supposed to fetch data from the following sources :

1. XML stored in a file system.
2. DataSet from another WebService
3. Service contracts from another service.

At first, this seems to be a mundane tasks, because you may have to create different code for different datasources and different translation for those datasources because an xml data is not the same as object data until we have a translator, we would not get anywhere near what we want to achieve.

First thing that comes to my mind was to leverage the Linq API and architecture to archive the above problem, how do i program my WCF service so that it will be extensible to other datasources, how do i ensure that the translation is not ambiguous (hence finding a better approach and framework that is consistent enough to do the job of translating data coming from different sources.

The Proposed architecture

I dig my hands into the dirty chests of patterns, i traveled from Gang of four to Microsoft pattern, i moved from different community, but there seem not to be a proper way of ensuring a consistent data translation strategy. After sometime, of digging, i eventually choose to use the interpreter pattern (Since it is used to interpret sentences in language elements). The reason for this choice is because i need a consistent language lexical structure that i can use for different data sources (as explained above) and Interpreter pattern seem to be the best choice to define my language grammar.


In this example, we want to interpret a Customer detail data structure coming from different sources, here is the C# structure of our Customer Poco class.



public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public int Age { get; set; }
}


We want to be able to translate several data sources to the Customer class defined above. This example will focus on the following data sources :

1. XML
2. Database
3. DataSet
4. object

If we are familiar with the Linq API, we would know that it supports for language elements across the named data sources above.

Interpreter Pattern Structure

The base interpreter is the interface to which we will use to interpret our language elements, because we need not know about the child classes or how they do their interpretations. The code snippet below is our base Interpreter.


public abstract class CustomerExpression
{
public Customer Customer { get; set; }
public abstract void Interpret();
}


The code above defines the CustomerExpression class and this class will define the structure of its child classes, the following child classes will be created :

  1. CustomerXMLExpression
  2. CustomerSQLExpression
  3. CustomerDataSetExpression
  4. CustomerObjectExpression
I will be discussing the first one only which is the CustomerXMLExpression. The code below is the snippet for the CustomerXMLExpression :



public class CustomerXMLExpression : CustomerExpression
{
public override void Interpret()
{
Customer = TranslateCustomer();
}

private Customer TranslateCustomer()
{
StringBuilder customerXML = new StringBuilder("XML Data");
XDocument customers = XDocument.Parse(customerXML.ToString());

return (from customer in customers.Descendants("Customers")
select new Customer
{
FirstName = customer.Element("FirstName").Value,
LastName = customer.Element("LastName").Value,
Age = (int) int.Parse(customer.Element("Age").Value),
Address = customer.Element("Address").Value,
}).FirstOrDefault();
}
}

We can use the same idea for the rest of the remaining data sources, for example we can search each data sources as follows :



CustomerExpression expression = new CustomerXMLExpression();
Customer customer = expression.Interpret();

CustomerExpression expression = new CustomerSQLExpression();
Customer customer = expression.Interpret();

CustomerExpression expression = new CustomerDataSetExpression();
Customer customer = expression.Interpret();

CustomerExpression expression = new CustomerObjectExpression();
Customer customer = expression.Interpret();



There is a long way you can go with this practise because it makes you to centralise your code and hides several dirty works away from developers.

Thursday, November 27, 2008

Enum can now have method

Thanks to Extension method.

Have you ever programmed against enum in the .NEt framework. Have you realized that the .NEt enum is not as efficient as other enum living in other platforms like the Java Land. Still the .NET enum is suffering from advance ways of using constants. An .NET enum cannot even have a method (Thats how bad it is) this is referred to constants specific method in Java.

But with the method extension in the .NET framework 3.5, we can pro grammatically extend an enum with methods that makes us think that they are actually defined within the enum scope.


public enum MyEnum
{
Name,
Age,
}

public static string RealName(this enum myEnum)
{
return Enum.GetName(typeof(MyName), myEnum);
}

MyEnum enn = MyEnum.Name,

enn.RealName();

Wednesday, November 26, 2008

Pragmatic Approach To development. (Developing for Today and Tomorrow)

Recently i have been engrossed in a project that will contribute to the way we develop system rapidly. This project is an ORM framework that maps the impedance mismatch between the relational world and the object oriented world. I must confess its one of those projects that does not have a finished date, its a project that will continuously apply the current trend in our no destination journey of system development. What i meant by no destination is that software evolves overtime and there is no promise land, is either we re-invent the wheel and make it a better wheel or we introduce a new form of practices or complexity.

I started on this project out of frustration because designing data access frameworks per the project isn't a good development practice this can lead to inconsistent development methodologies and framework will be prone to errors. In my software development lifetime i have worked on several real world projects in their hundreds, and i understand fully well what fits well in what area. Dont get me wrong, i do mistakes too, but i accept these mistakes immediately and i make it my strength. So, over the years, i have struggled to find a long lasting solutions to poor and repeated programming approach.

Develop For Tomorrow

One of the greatest software practice i have learn't is not letting requirement to control the software but letting the software development process think ahead of what the requirement maybe in the nearer future. This is a proactive approach to developing a scalable and reliable applications that will cut across different environment and requirements.

Most of us, developers allow software requirements to drive and predict the architecture of our software for us, so when requirement changes, we need to change heavy chunk of our code. To me thats a very bad approach and it could be very costly to organisations that are practicing such approach. Where is separation of concern, where is pragmatic development.


Requirement Volatility does not mean software volatility

Feasibility checks should be done on requirements before the changes can be made. Even without full requirement, software should be built with adaptability and reconfigurability in mind, this will ensure that the volatility nature of requirements does not affect system development.


Separate as many concern as you like

Recently, in Microsoft (MSDN) Forum, somebody asked a question about separating the a UI framework or layer from a data layer, many suggestions where given to this question, some say use DTO (Data transport Object) some say use interface, the bottom line is use something that wont have adverse effect on your codebase even when the underlying structure changes, be very pragmatic and scrutinize the kind of changes that are anti pattern, we are not in the procedural programming ERA, we are developing in the world of Objects (Think in objects).

Beware of hard-coding
One of the major setback of good programming practices is hard coding. When developers hard code, it shows how vulnerable our codes can be, and how it is difficult to maitain and sustain. I wonder why we will leave a pragmatic approach to development (Even if it takes time, lets do it right). So never hard code, instead create constant file or xml or use enum.

Command architecture and dependency injection

On a recent project, we were mapping commands to user intentions, covering all aspects pertaining to the usage of the application from the p...