Reaching post-conditions in tasks

Implementing use cases in Adf.Net is covered by the task pattern. Each smart use case in the model is implemented as a descendant of the Task class in Adf.Net.

The task pattern consists of three major parts:

  • Starting the task, either using a parameterized Init() method, or the default Start() method.
  • After a task calls another task, and this second task is finished, control goes back to the calling task, using any of the specific ContinueFrom() methods, or the default Continue() method.
  • When a task reaches any of the post-conditions of a task, the task needs to be ended, usually through the Ok() or Cancel() method.

In this specific post I’ll look at reaching the post-conditions. In the pattern, the Task class itself acts as the layer super type and implements a number of method to end itself. A use case can have multiple post-conditions. Some of them are positive, some can be negative. And sometimes a specific case needs to be addressed.

When a reaches it positive post-condition, it is a best practices to end it using the Ok() method. This method takes a params object[] p, which allows you to pass back results from the task to the calling task, using the following signature.

public virtual void OK(params object[] p);

A similar method Cancel() exists for task that end in a negative post-condition, usually because the user cancels the interaction:

public virtual void Cancel(params object[] p);

But, Adf.Net also supplies a similar method Error(), to allow tasks to finish with an error, possibly technical.

Under the covers, these three methods call on another method, which is called Finish(). This method takes care of passing back an instance of TaskResult. This result also gets posted back to the calling task, so it knows how the called task has ended. As in the following example, you could also use Finish() yourself.

if (persoon.IsNullOrEmpty())
{
    ValidationManager.AddError(GEENPERSOONGESELECTEERD);
    Finish(TaskResult.Error);
}

Please note that the code above is equal to the following code.

if (persoon.IsNullOrEmpty())
{
    ValidationManager.AddError(GEENPERSOONGESELECTEERD);
    Error();
}

By default, TaskResult has the following values in Adf.Net: Ok, Cancel, Error.

However, as TaskResult is implemented using the descriptor pattern, additional project specific value can be added easily, by inheriting from TaskResult, and added the specific values. Thus you would be able to end your task in more project specific ways, such as in the code example below.

if (persoon.IsNullOrEmpty())
{
    ValidationManager.AddError(GEENPERSOONGESELECTEERD);
    Finish(Dashboard8TaskResult.Aborted);
}

Modeling your domain models in UML

In any given system under development, the business domain of that system is key. It holds all concepts important to the domain, and captures the business logic from the domain. An important question to answer is what to model about the objects in that domain and how to model this in UML class diagrams.

Identifying the elements of the business domain

First of all, it is important to underline which types of classes participate in the model, simply referred to as the domain model. Aligned with the paradigm of domain driven design, I recommend to model the following types of classes:

  • Domain objects.
  • Factories.
  • Repositories.
  • Services.

Domain objects

A domain object captures a concept from the real world of the application. Think of Contact, Contract, Company or Address. Domain object are considered to have identity. Next, domain objects have properties, and these properties have types. Also, domain object deliver services (often implemented as methods).

image 
A number of domain objects in a class diagram

A concept in the business domain should be considered as such if it has either state (modeled in properties) or delivers services (modeled as operations). Or of course both.

Factories

Factory classes are used to create new instances of domain objects. Although this can often be achieved by just directly creating a domain object from scratch, in most domains creating new object is more complex, especially with the core concepts in the business domain. For instance, when we created a new Contact, it need to have a least one Address which also needs to be created, and it should be aligned with the current Company. When creating such a construct (often referred to as a aggregate in domain driven design) a factory class is used (and modeled) to holds this creation functionality.

A factory class can cover multiple creation scenarios. Name your factory classes after the domain object it creates. Think of classes such as ContactFactory and CompanyFactory. Model each of these scenarios as a method on the factory class.

Repositories

Additionally to the factory classes, a business domain can have repositories. A repository is responsible for answering enquiries about existing instances of domain objects. For instance, you might want to grab all instances of Contact who live in Amsterdam. Name such repositories after the corresponding domain object. Think of ContactRepository or AddressRepository. Model such enquiries as methods on the repository associated with the domain object. Please note that many projects choose to combine the factory and repository classes.

Services

Some services in the business domain do not directly correspond to a domain object, but rather apply to several different domain objects. In this case, such as service can be modeled as a separate class, usually with the name of the actual task as its class name. Think of a service such as  ImportFromExcel that imports a project, its work items and their estimates into a dashboard.

As an alternative, projects may choose not to model separate factories, repositories and services, but rather add all their functionality as services on the actual domain object. In this case, I would recommend stereotyping these methods for example as factory method, repository method or service, so their purpose is immediately clear.

Please note that even though now these methods are modeled on the domain object, they will likely not be implemented there, but on the actual factories and repositories. This alternative is merely a technique to avoid cluttering the domain model with unnecessary classes. Domain models are full enough without adding factories and repositories.

Identifying properties

Now let’s delve down to the domain objects, clearly the most important type of class in the domain model. Next to delivering services, domain objects have properties, such as Name, Email, City, Country, Level.

image
A domain object Contact with a number of public properties

You will need to identify all meaningful properties on your domain objects. Basically you will need to identify all properties that a domain object exposes to the outside world, either other classes in the domain, user interface elements that bind to it, use cases or persistency layers. These are the public properties of the domain object.

Do not model fields that are internal to a domain object as these are not relevant to the business domain but in most cases are only relevant to the developers. Thinks for instance of the Id of a domain object, that is required to store it in a database or to a web service.

A special reminder goes out to properties that are not persisted but are calculated or assembled by the other properties and fields of the domain object. These are called derived properties, and should be marked as such in the domain model.

Modeling property types

And each of these properties has a type. These types actually hold quite a lot of information on the business domain – maybe even more than you’d expect.

I consider the following types of property types:

  • Basic types such as string, DateTime, float.
  • Values types or objects such as ISBN, Email or BSN.
  • Enumerations
  • Variable lists.
  • Associations.

Basic types

Many properties will appear to have a basic type, such as number, string, date, timestamp, float. However, note that for a whole lot of properties, you actually quite a lot more than that it’s just a string. Therefore, for each property check properly if you know more about it than that it just has a basic type.

Value types or object

A value type or object is an object that is recognizable by its value, but where we are not interested in it’s identity. For instance, two instances of my email address will appear to be the same, while two instances of Company that can have exactly the same values for all properties can still be two different companies.

Enumerations

Sometimes, a property can only have a limited set of values. In this case you might consider modeling an enumeration (which is a standard stereotype in UML). This enumeration holds the possible values, so next you can model the property of the type of the enumeration.

image
Enumerations ContactType, PrivacyLevel and Gender.

For instance, a domain object Contact might have a Type property that be Individual, Group or Family. Now model an enumeration ContactType that holds these values, and model the property Type of type ContactType.

But, there’s a restriction to using enumerations. Only use these if you are certain that the list of possible values is static, that is does not change over the course of the life of you application. If you need to add to or change the list of values, this results in re-testing your whole application as the values are often used to perform conditional operations. So if you think the list of values is going to change don’t use an enumeration. Model a variable list instead.

Variable lists

If a property can only have a value from limited set of values, but that list is subject of change during the life of your application, enumeration are not the best solution. The list of values itself should be maintained – either by some software, possibly external to your application, or directly in the database. Think of lists of countries, states or academic titles.

Therefore you will need to take extra care of these properties. Now there’s a number of options here. If the list only uses standard properties (think of Name and Description) and is just used for reference, you might want to group all these different list into one single domain object (and hence table). In this case, an additional properties is required for this domain object, for instance called Type, that describes the type of element, such as Country, State, or AcademicTitle. In this option you will only need a single maintenance use case to maintain all values in all lists. The value or now available for reference, selection or printing on envelopes. We usually refer to this pattern as Smart Reference.

For modeling a property of the type of such a variable list there are a number of options. Either refer to the type of list in the name of the property (call it Country, State or AcademicTitle) and model SmartReference as the type of the property. This works out fine as long as you don’t have to properties of a domain object referring to the same variable list.

A more agreeable option is to give the property the name you want it to have, and model the type of the variable list as the type of the property. To make sure the property is recognized as a variable list, add a stereotype (for instance smartreference) tot the property.

Associations

And then there’s the option that would want to refer another domain object. In this case you normally model an association rather than model a property. An association models a structural relationship between two (or more, but don’t go that road) objects in your business domain. So if a contact has zero, one or multiple relationship, you can model this as a one-to-many association between the domain object Contact and Relationship in your domain model.

image
Two (named) associations between Contact and Relationship.

In code all associations (as in UML) are represented by properties that exist on both classes. So in the example Contact will have a property that represents a list of relationships. And vice versa, each Relationship will have a property of type Contact. Unless you add additional names to the ends of the association in the domain model, the names for these properties are undefined. However it’s a good habit to name them after the domain object they come from. So the properties will simply be called Contact.Relationships and Relationship.Contact – mind the plural.

However, if there’s two different associations between the same domain objects, applying this default naming patterns isn’t enough. It would result in multiple properties with the same name. In that case always specify meaningful names explicitly to the ends of the association. For instance if another association (one-to-one) between Contact and Relationship exists that identifies who’s the from and who’s to to in the relationship, this could result in properties Contact.Froms (a list of type Relationship) and something like Contact.Tos (also a list of type Relatioship).

Another reason for specifying meaningful names to association ends is that these simply occur in the vocabulary of the business domain.

Adding validations

The next step is to add validations to you domain model, and your domain objects in particular. I’ll look at the following types of validations:

  • Are properties mandatory or not?
  • Is the property valid if the type is a value object?
  • Is the property correctly formatted?
  • Does the domain object adhere to the defined business rules?

Mandatory properties

Most properties on domain objects will be mandatory (although debatable). Therefore by default the multiplicity for a property is set to [1..1], which means that there is to be exactly one occurrence for this properties on each object. If a property is not mandatory for the domain object to be valid the multiplicity of such a property is set to [0..1] – which implies that zero or one instances of this property are present.

image
Mandatory and non-mandatory properties

In the example above, BirthName is not mandatory, but AlternativeEmail2 is.

Value objects

The use of value types of objects in your domain objects explicitly adds validation to your objects. It means that the validations rules for this particular value object will apply to such a property automatically. If a property is defined using type Email, all values (when checked) need to follow the rules defined on the value object Email that define when something is in fact a valid Email. Of course, these validations can best be modeled on the value object itself.

image
Properties that have a value object as their type (Email)

In code, this could results in the following property for class Contact (using the ADF.NET framework).

   1: public Email AlternativeEmail2
   2: {
   3:     get { return state.GetValue<Email>(ContactDescriber.AlternativeEmail2); }
   4:     set { state.SetValue(ContactDescriber.AlternativeEmail2, value); }
   5: }

Formatting

Some properties follow a certain format. Think of properties representing money or dates. If the type of the property is a value object, the format should be specified there (often as a regular expression). If not, model the format with the property. Please note that formatting is often culture specific.

Formats can include aspects such as length attributes, for instance a string may not be longer than 64 characters, or must be within a certain range, for instance when a value must be larger than 0 but smaller than 128.

Business rules

Additionally domain objects can validate business rules. For instance on a domain object Relationship, a business rule may validate that both contacts in the relationship match some relationship type. This can be defined in an operation (or a method in code) called ToContactMustMatchRelationshipType. Although this seems like an abundant long name, in fact I recommend to name business rules exactly to what they’re actually doing. Moreover, I recommend to implement the business rules in code using exactly the same name, thus creating traceability.

image 
Modeling business rules in your domain object using the business rule stereotype

I also recommend to add the stereotype business rule to these operations to distinguish them from other methods your classes have. In code the business rule ToContactMustMatchRelationshipType could look something like this. Here the attribute BusinessRule is attached to the method for the same reason, and to allow for automatic validation.

   1: [BusinessRule]
   2: public ValidationResult ToContactMustMatchRelationshipType()
   3: {
   4:     return !To.IsEmpty && RelationshipType.To != To.ContactType
   5:         ? ValidationResult.CreateError(this.Prop(r => r.To), "Contact type '{1}' for {0} does not match required contact type '{2}'.", To, To.ContactType, RelationshipType.To) 
   6:         : ValidationResult.Success;
   7: }

 

An interesting type of business rule is that where the domain object at hand is validated against other domain object (mostly of the same type). For instance, when adding a new OrderType object, even though it is by definition unique (as domain object have identity by nature, usually implemented using an Id property), may not have the same name as any of the other already existing order types. Or a new contract

When to validate?

An intriguing question that comes to mind when discussing validation is when to validate the validations? In a traditional Windows user interface one might say that the moment the user leaves a field and moves to the next the validation for the represented domain object property could or should be fired. In a web application typically the user types in all the fields and then presses submit.

Validating the objects at hand should fire all validations, value objects, mandatory properties, formatting, business rules that are valid for the event (such as save, remove). In the code example from use case Manage Address an Address object is validated and than saved .

   1: public void SaveAddress()
   2: {
   3:     
   4:     if (this.Execute(
   5:         () => Address.Validate(),
   6:         () => Address.Save(),
   7:         () => SaveContact()))
   8:     {
   9:         OK();
  10:     }
  11: }

How Smart Use Cases Can Drive Web Development. Video for session at DevDays 2011 [in Dutch]

as the Channel 9 website says: using real-life code examples Sander will demonstrate how to model, generate and build smart use cases and introduce the positive impact smart use cases have on your layered software architecture.

Anyway, here’s the video for my DevDays 2011 session:

November 12, 2010 – Microsoft TechEd Europe. How smart use cases can drive web development

[Session ARC205 at Microsoft TechEd Europe 2010 in Berlin]

Use cases have been around for many years describing the requirements of software development projects. From a developer’s point of view, use cases are often seen as too abstract and too complex to develop code from. Until now, that is.

IMAGE_004[5]

During this interactive talk, speaker Sander Hoogendoorn will demonstrate how to model, generate and build smart use cases.

image[8]_thumb[2]

This great technique allows you to model use cases at a much more pragmatic, low-granular level, enabling them to be implemented simply and directly into applications such as ASP.NET or Silverlight. Using many real-life code examples, the speaker will introduce both the positive impact that smart use cases have on your layered software architecture, as well as the design patterns required to implement them.

November 9, 2010 – Microsoft TechEd Europe. How frameworks can kill your projects.

[Session ARC203 at Microsoft TechEd Europe 2010 in Berlin]

When it comes to Microsoft .NET-connected development, more and more frameworks are entering the market, both from Microsoft and from open source. Think of ASP.NET MVC, Castle, Windows Workflow Foundation (WF), Entity Framework, Unity, Linq2SQL, ADO.NET Data Services, Windows Communication Foundation (WCF), nHibernate, Spring.NET, CSLA, NUnit, Enterprise Library, MEF or ADF.

IMAGE_004

Once you apply one or more frameworks to a project, the trouble begins. What if you require features that aren’t implemented in the framework? What if you decide that another framework would have been better and want to switch halfway through your project? What if the author of your favorite open source framework suddenly stops developing? What if the framework contains bugs or omissions? And what if a new version of the framework is released that is implemented differently?

image[8]

 

These and many more everyday problems can bring your project a halt, or at least require serious refactoring. During this highly interactive talk, Sander Hoogendoorn, chief architect of Capgemini’s agile Accelerated Delivery Platform and member of Microsoft’s Partner Advisory Council .NET, demonstrates pragmatic architectures and patterns that will help your projects avoid framework issues and to keep code independent of framework choices. Sander presents models of layered architectures, and looks at applying bridge patterns, managers-providers, dependency injection, descriptors and layer super-types, accompanied by lots of demos and (bad) code examples using blocks from Microsoft’s Enterprise Library, NHibernate, Log4Net, and the Entity Framework.

Join this interactive discussion to share your experience of improving the structure and quality of your software architecture and code, and to discuss how to avoid common pitfalls of applying frameworks to .NET software development.

Sander’s talk at TechEd US 2010. How frameworks can kill your projects and patterns to prevent getting killed

Last week, the Microsoft TechEd North America 2010 took place in the great city of New Orleans. I was lucky to be invited to do a talk on how frameworks can kill your projects.

When it comes to Microsoft .NET-connected development, more and more frameworks enter the market. Both from Microsoft and from open source. Think of ASP.NET MVC, Castle, Windows Workflow Foundation (WF), Entity Framework, Unity, Linq2SQL, ADO.NET Data Services, Windows Communication Foundation (WCF), nHibernate, Spring.NET, CSLA, NUnit, Enterprise Library or ADF.

Trouble begins

Once a project chooses to apply one or more frameworks, trouble begins. What if you require features that aren’t implemented in the framework? What if you decide that another framework would have been better and want to switch halfway through your project? What if the author of your favorite open source framework suddenly stops developing? What if the framework contains bugs or omissions? And, what if a new version of the framework is released that is implemented differently? These and many more everyday problems will cause your project to come to a halt, or at least make you perform serious refactoring.

Get Microsoft Silverlight  

Demos and (bad) code

During this highly interactive talk, Sander Hoogendoorn, chief architect of Capgemini’s agile Accelerated Delivery Platform, and member of Microsoft’s Partner Advisory Council .NET, demonstrates pragmatic architectures and patterns that will help your projects to stay away from framework issues, and how to keep code independent of framework choices. Sander presents models of layered architectures, and applying bridge patterns, managers-providers, dependency injection, descriptors, and layer super-types.

Of course, Sander illustrates these insightful patterns with lots of demos and (bad) code examples using blocks from Microsoft’s Enterprise Library, NHibernate, Log4Net, and the Entity Framework. Learn how to improve the structure and quality of your software architecture and code, and how to avoid the pitfalls of applying frameworks to .NET software development.

Extension methods (with DevDays 2010 slides)

This post was originally published in .NET Magazine. I re-posted it because of the talk I did at Microsoft’s DevDays 2010 in Den Haag recently.  The slides for this talk can be downloaded here.

As you’re probably have been made aware of in abundance, in .Net 3.5 Microsoft introduced a little language feature called LINQ. Although LINQ has been demonstrated at all major and minor conferences, the way LINQ executes queries on already existing types remained slightly less apparent. To this means LINQ introduces a number of new query operators, using yet another new language  feature called an extension method.

Download slides from my DevDays 2010 talk on extension methods here.

 

Basically, there are two sets of LINQ query operators. One set that operates on objects of type IEnumerable and another set that operates on objects of type IQueryable. To implement the methods in these sets, the .NET architects chose to add something called extension methods, and write the required methods as extension methods to the Enumerable and Queryable classes, instead of directly extending these classes – which would seriously pollute the .NET framework.

Defining a simple extension method

Apart from the apparent use of these extension methods in the query operators of LINQ, there is slightly more to it. At first sight, extension methods appear to allow you to extend any class in any namespace with additional functionality. Let’s have a closer look at them by using an example.

One of things I always disliked about working with the DataSet class is that to obtain the value from a column in a row in a table, I’d have to write code that looks at lot like this:

public void DoTraditionalTest()
{
    DataSet ds = new DataSet();
 
    object o = ds.Tables[2].Rows[4]["Name"];
}

This code is both tedious and poor code however, as it doesn’t do any check on whether the table and row are actually available. As you’ve probably all have written code like this before, you would probably have appreciated a method like Get() on the DataSet class, like I’m using in the following code example, where Get() performs all necessary checks and formatting.

public void DoTest()
{
    DataSet ds = new DataSet();
 
    object o = ds.Get(0, 0, "Name");
}

The issue here is that you cannot extend the .NET framework class DataSet to encapsulate this functionality. This is where extension methods come in neatly. With .NET 3.5 I can now write a method such as the following.

namespace Extensions
{
    public static class DataSetExtensions
    {
        public static object Get(this DataSet ds, int table, int row, string column)
        {
            if (table >=  0 && table <= ds.Tables.Count)
            {
                if (row >= 0 && row <= ds.Tables[table].Rows.Count)
                {
                    return ds.Tables[table].Rows[row][column];
                }
            }
 
            return null;
        }
    }
}

If you’ve never seen an extension method before, the first parameter will appear strange to you. The this keyword is added to it to show that this Get() method works on the DataSet class. Although this method is defined as a static method on a class called DataSetExtensions, it is recognized as an instance method on the DataSet class.

image

Intellisense even recognized my method, and the code comments I’ve added. The only difference between an instance method and an extension method from an intellisense point of view, is that you’ll still be able to notice the this parameter in the signature of your extension methods. Of course, the same goes for .NET framework defined extension methods, like the LINQ Where() method, which also displays the this parameter.

image

Extension methods and the Open Closed Principle

Doesn’t that look cool? I think so. When I first read about extension methods I immediately thought of a whole bunch of functionality that I could add not only to our own frameworks, but also to open source and  even the .NET framework itself. But before bloating out lots of code, let me give you some caution.

My biggest worry was whether extension methods would allow me to break existing framework code. There’s a well known principle that needs to be examined here, which is called the Open Closed Principle (OCP). In short, this principle states that classes should be open for extension, but closed for moderation. In general I think this is a principle well worth living by. So, the big question is: do extension methods allow me to change the behavior of existing classes? What happens if I write an extension method, such as the one below?

namespace Extensions
{
    public static class ObjectExtensions
    {
        /// <summary>
        /// Testing whether I can override the ToString() method.
        /// </summary>
        /// <param name="o">The object</param>
        /// <returns>My own string.</returns>
        public static string ToString(this object o)
        {
            return "Sander is always right.";
        }
    }
}

The question is, by writing this simple extension method, did I just override the ToString() method for all classes in my applications? Surely, such extension methods would kill a lot of projects really fast. Of course the .NET architects do not allow you to do so. There’s thing or two you should know about how extension methods work, and about how they are compiled.

Compiling extension methods

First, they’re defined within the context of a namespace, Extensions in the example above. To use an extension method on a class in your code, you will need to add a reference to the namespace that contains the extension methods. Without this reference, the method don’t even show up.

Second, and even more important, extension methods are in fact just static methods on a static class, as can be seen in intermediate language (IL). Extension methods only appear in your code editor as instance methods on the target class. The fact that they’re defined as static methods outside of your target class means that in an extension method you can only get to the public properties the target class exposes, but you will not be able to reach the protected and private fields of this class, nor will you be able to define new properties or fields.

Even more important, it is interesting to notice what the compiler does with your extension methods, especially in the case that you would define a method with the same signature as the method in the target class, like with the ToString() method above.

The compiler follows a straightforward rule: extension method always have a lower priority that real instance methods. As a consequence, when the compiler tries to resolve a method invocation it first looks in the target class for methods with matching signature, and consequently in its ancestors, and bind to this method if located. Only if no instance method is found, will it start to look for extension methods with the same signature. Following this convention the ToString() method I’ve defined above will never be called, as the object class defines a method with a matching signature.

Even when I try to create a (very stupid) extension method like the one below, targeting the Equals(string s) method just for matching with a string, the compiler will still bind to the Equals(object o) method from the object class, even if it has a wider scope – it compares with an object, not a string.

public static bool Equals(this object o, string match)
{
    return match.Contains("Sander");
}

This compiler directive satisfies my concerns. Using extension methods, you will not be able to alter any existing functionality. You can not override existing methods, nor get a hold of private or protected fields. In fact, the extension method totally live outside of the target class. So, you’re quite safe.

No worries then?

Well, there’s something else that concerns me about extension methods. The most demo’s I see on extension methods worry me. There seems to be no end to people extending the String class. I’ve seen demo’s that check whether a string is a valid email address, a valid URL, and even extensions that speak out a string using a synthesizer – although I expect good craftsmanship, not really something I long for in my applications.

It’s just that stuff like this should not be extensions to the string class. Unless at least 50% of all strings you use in your code are in fact email address, I would consider a different pattern here, such as defining value objects of type Email, Zip or whatsoever. In general, my concern with extension methods is that it’s such a neat little technology, that it will invite people to use it for all the wrong reasons – just because it’s fun to define an extension method for instance.

Before you know it, the developers in your project will have defined loads of extension methods, to all kinds of framework classes. You should be well aware of the possibilities this offers to break your application architecture and create lots of undesired dependencies. Just take a quick look at the following example.

using System.Workflow.Activities;
 
namespace Extensions
{
    public static class CodeAcitivityExtensions
    {
        public static bool Kill(this CodeActivity activity)
        {
            activity.Dispose();
        }
    }
}

Here, I’ve added an extension method to the CodeActivity class, which resides in the namespace System.Workflow.Activities. Now my Extensions namespace has a dependency on this namespace, and moreover, also on the underlying System.Workflow.ComponentModel namespace.

However, my previous code example where I extended the  DataSet class also resides in my beautiful Extensions namespace. So from this day forward, every time I use my Get() extension method for DataSet, I’m indirectly also connected to the workflow namespaces. Just as an example.

Furthermore, when you define an extension method to extend a type delivered by a framework, you also run the risk that your extension method will cause your code to break if the implementation of that type changes, or if your project migrates to a newer version of that particular framework, of .

Extending framework base classes

On the good side, you will more likely use extension methods that other developers have written, than define your own. Here, extension methods are a powerful features, as applying extension methods does not require any additional knowledge. Most extension methods will be written by frameworks developers, who now will feel enabled to solve anomalies. Or even more likely by developers who feel the need to extend base classes from existing frameworks, both from Microsoft and open source, such as in the following example, that extends the open source frameworks CSLA.

One of the most reused base classes in the CSLA framework is called BusinessBase. It serves as layer supertype for all domain objects in applications built with the framework. The BusinessBase class has the ability to validate its business rules. To this means it stores a broken rules collection that contains references to business rules that are violated during a validation of your domain object.

In some cases, for instance when displaying violated business rules on screen, it can be handy to know which business rules were broken per property. The BusinessBase class however, does not have this ability.

public static IEnumerable<BrokenRule> GetBrokenRules(this BusinessBase bb, string property)
{
    var queryableList = new List<BrokenRule>(bb.BrokenRulesCollection);
    IEnumerable<BrokenRule> result;
    if (!string.IsNullOrEmpty(property))
    {
        result = from brokenRule in queryableList
                 where brokenRule.Property.Equals(property)
                 select brokenRule;
    }
    else
    {
        result = queryableList;
    }
    return result;
}

The code example here displays an extension method for BusinessBase that loops through the total collection of broken rules using a LINQ query that filters the broken rules for the selected property (using the property’s name). This method is very useful and powerful example of how developers can tweak the functionality of framework classes. It should come as no surprise that many more such extension methods will become available from the community soon for popular frameworks such as Microsoft’s Enterprise Library, nHibernate, ADF, CSLA and of course for the .NET framework itself.

Handle with care

Extension methods are a language feature that does not really stand out in the crowd, but can be very useful, especially to avoid repetitive work that should have been a feature of frameworks you apply to your projects. However, when developing extension methods you will need to be very aware of the side effects described above. I therefore recommend to implement extension methods sparingly. Under normal circumstances, you will still extend existing types by inheriting from them, even though this requires your developers to use your new class by convention instead of an extended base class. To leave you with a proper quote: “Creativity is a natural extension of our enthusiasm.”

Pragmatic model driven development. Part III. Creating the domain model

Note. This series of posts is also published as a Capgemini group white paper and published in Software Release Magazine (in Dutch, in two parts).

The next step towards generated code, and other deliverables, is to create the domain model for the project. Next to the smart use cases, that capture the desired behavior, the domain model provides a structural view of the system.

Roughly said, the domain model captures the key concepts, types, rules, validations, and services of the business domain, expressed in customer terminology. Furthermore,  the model identifies the relationships between all major types.

In this pragmatic approach we follow and extend on the principles stated by Eric Evans in his domain driven design paradigm. As your might expect, the domain model is expressed in UML class diagrams. Primarily, the domain model models domain objects (or entities) such as Customer, Order, Subscription or Course and their relationships, expressed as associations. Next, the properties and their types are modeled.

image17

We consider five different categories of property types, that are all applicable in different situations:

  • Basic types. In general, people tend to model property types in basic types, such as string, integer, boolean or date. However, we have more knowledge on most property types than that it’s just a string or integer. In this case it’s better to use value objects.
  • Value objects. A value object holds no identity, but reflects a value. In short, value objects are good for modeling property types that can be validated, such as Bsn, Isbn or Email.
  • Enumerations. We model property types as an enumeration, if the property can only have a limited, fixed number of different values. Think of ContractType, Gender or Level.
  • Smart references. Another pattern we apply to modeling property types, is the smart reference. We have agreed to model a property as smart reference if the property can only have a limited, but possibly changing number of different values. Here you could consider properties such as Department, Prefix or Country (if no other information on countries is required).
  • Associations. If a property has a type that itself is a domain object, we model an association. Note that in UML an association is actually defined as properties on both ends of the association.

Each of these categories of property types can be used nicely in code generation. For instance, enumerations and smart references can be used to fill drop down lists, and associations of course can be used to generate master-detail behavior or object-relationship mapping configuration files. Moreover, the multiplicity, role names and composite parts of associations can all be used in code generation.

Extension methods. The overlooked language feature

This post was published in .NET Magazine. I recently did a talk at the SDC Conference at Papendal, Arnhem, discussing this topic.

As you’re probably have been made aware of in abundance, in .Net 3.5 Microsoft introduced a little language feature called LINQ. Although LINQ has been demonstrated at all major and minor conferences, the way LINQ executes queries on already existing types remained slightly less apparent. To this means LINQ introduces a number of new query operators, using yet another new language  feature called an extension method.

Basically, there are two sets of LINQ query operators. One set that operates on objects of type IEnumerable and another set that operates on objects of type IQueryable. To implement the methods in these sets, the .NET architects chose to add something called extension methods, and write the required methods as extension methods to the Enumerable and Queryable classes, instead of directly extending these classes – which would seriously pollute the .NET framework.

Defining a simple extension method

Apart from the apparent use of these extension methods in the query operators of LINQ, there is slightly more to it. At first sight, extension methods appear to allow you to extend any class in any namespace with additional functionality. Let’s have a closer look at them by using an example.

One of things I always disliked about working with the DataSet class is that to obtain the value from a column in a row in a table, I’d have to write code that looks at lot like this:

public void DoTraditionalTest()
{
    DataSet ds = new DataSet();
 
    object o = ds.Tables[2].Rows[4]["Name"];
}

This code is both tedious and poor code however, as it doesn’t do any check on whether the table and row are actually available. As you’ve probably all have written code like this before, you would probably have appreciated a method like Get() on the DataSet class, like I’m using in the following code example, where Get() performs all necessary checks and formatting.

public void DoTest()
{
    DataSet ds = new DataSet();
 
    object o = ds.Get(0, 0, "Name");
}

The issue here is that you cannot extend the .NET framework class DataSet to encapsulate this functionality. This is where extension methods come in neatly. With .NET 3.5 I can now write a method such as the following.

namespace Extensions
{
    public static class DataSetExtensions
    {
        public static object Get(this DataSet ds, int table, int row, string column)
        {
            if (table >=  0 && table <= ds.Tables.Count)
            {
                if (row >= 0 && row <= ds.Tables[table].Rows.Count)
                {
                    return ds.Tables[table].Rows[row][column];
                }
            }
 
            return null;
        }
    }
}

If you’ve never seen an extension method before, the first parameter will appear strange to you. The this keyword is added to it to show that this Get() method works on the DataSet class. Although this method is defined as a static method on a class called DataSetExtensions, it is recognized as an instance method on the DataSet class.

image

Intellisense even recognized my method, and the code comments I’ve added. The only difference between an instance method and an extension method from an intellisense point of view, is that you’ll still be able to notice the this parameter in the signature of your extension methods. Of course, the same goes for .NET framework defined extension methods, like the LINQ Where() method, which also displays the this parameter.

image

Extension methods and the Open Closed Principle

Doesn’t that look cool? I think so. When I first read about extension methods I immediately thought of a whole bunch of functionality that I could add not only to our own frameworks, but also to open source and  even the .NET framework itself. But before bloating out lots of code, let me give you some caution.

My biggest worry was whether extension methods would allow me to break existing framework code. There’s a well known principle that needs to be examined here, which is called the Open Closed Principle (OCP). In short, this principle states that classes should be open for extension, but closed for moderation. In general I think this is a principle well worth living by. So, the big question is: do extension methods allow me to change the behavior of existing classes? What happens if I write an extension method, such as the one below?

namespace Extensions
{
    public static class ObjectExtensions
    {
        /// <summary>
        /// Testing whether I can override the ToString() method.
        /// </summary>
        /// <param name="o">The object</param>
        /// <returns>My own string.</returns>
        public static string ToString(this object o)
        {
            return "Sander is always right.";
        }
    }
}

The question is, by writing this simple extension method, did I just override the ToString() method for all classes in my applications? Surely, such extension methods would kill a lot of projects really fast. Of course the .NET architects do not allow you to do so. There’s thing or two you should know about how extension methods work, and about how they are compiled.

Compiling extension methods

First, they’re defined within the context of a namespace, Extensions in the example above. To use an extension method on a class in your code, you will need to add a reference to the namespace that contains the extension methods. Without this reference, the method don’t even show up.

Second, and even more important, extension methods are in fact just static methods on a static class, as can be seen in intermediate language (IL). Extension methods only appear in your code editor as instance methods on the target class. The fact that they’re defined as static methods outside of your target class means that in an extension method you can only get to the public properties the target class exposes, but you will not be able to reach the protected and private fields of this class, nor will you be able to define new properties or fields.

Even more important, it is interesting to notice what the compiler does with your extension methods, especially in the case that you would define a method with the same signature as the method in the target class, like with the ToString() method above.

The compiler follows a straightforward rule: extension method always have a lower priority that real instance methods. As a consequence, when the compiler tries to resolve a method invocation it first looks in the target class for methods with matching signature, and consequently in its ancestors, and bind to this method if located. Only if no instance method is found, will it start to look for extension methods with the same signature. Following this convention the ToString() method I’ve defined above will never be called, as the object class defines a method with a matching signature.

Even when I try to create a (very stupid) extension method like the one below, targeting the Equals(string s) method just for matching with a string, the compiler will still bind to the Equals(object o) method from the object class, even if it has a wider scope – it compares with an object, not a string.

public static bool Equals(this object o, string match)
{
    return match.Contains("Sander");
}

This compiler directive satisfies my concerns. Using extension methods, you will not be able to alter any existing functionality. You can not override existing methods, nor get a hold of private or protected fields. In fact, the extension method totally live outside of the target class. So, you’re quite safe.

No worries then?

Well, there’s something else that concerns me about extension methods. The most demo’s I see on extension methods worry me. There seems to be no end to people extending the String class. I’ve seen demo’s that check whether a string is a valid email address, a valid URL, and even extensions that speak out a string using a synthesizer – although I expect good craftsmanship, not really something I long for in my applications.

It’s just that stuff like this should not be extensions to the string class. Unless at least 50% of all strings you use in your code are in fact email address, I would consider a different pattern here, such as defining value objects of type Email, Zip or whatsoever. In general, my concern with extension methods is that it’s such a neat little technology, that it will invite people to use it for all the wrong reasons – just because it’s fun to define an extension method for instance.

Before you know it, the developers in your project will have defined loads of extension methods, to all kinds of framework classes. You should be well aware of the possibilities this offers to break your application architecture and create lots of undesired dependencies. Just take a quick look at the following example.

using System.Workflow.Activities;
 
namespace Extensions
{
    public static class CodeAcitivityExtensions
    {
        public static bool Kill(this CodeActivity activity)
        {
            activity.Dispose();
        }
    }
}

Here, I’ve added an extension method to the CodeActivity class, which resides in the namespace System.Workflow.Activities. Now my Extensions namespace has a dependency on this namespace, and moreover, also on the underlying System.Workflow.ComponentModel namespace.

However, my previous code example where I extended the  DataSet class also resides in my beautiful Extensions namespace. So from this day forward, every time I use my Get() extension method for DataSet, I’m indirectly also connected to the workflow namespaces. Just as an example.

Furthermore, when you define an extension method to extend a type delivered by a framework, you also run the risk that your extension method will cause your code to break if the implementation of that type changes, or if your project migrates to a newer version of that particular framework, of .

Extending framework base classes

On the good side, you will more likely use extension methods that other developers have written, than define your own. Here, extension methods are a powerful features, as applying extension methods does not require any additional knowledge. Most extension methods will be written by frameworks developers, who now will feel enabled to solve anomalies. Or even more likely by developers who feel the need to extend base classes from existing frameworks, both from Microsoft and open source, such as in the following example, that extends the open source frameworks CSLA.

One of the most reused base classes in the CSLA framework is called BusinessBase. It serves as layer supertype for all domain objects in applications built with the framework. The BusinessBase class has the ability to validate its business rules. To this means it stores a broken rules collection that contains references to business rules that are violated during a validation of your domain object.

In some cases, for instance when displaying violated business rules on screen, it can be handy to know which business rules were broken per property. The BusinessBase class however, does not have this ability.

public static IEnumerable<BrokenRule> GetBrokenRules(this BusinessBase bb, string property)
{
    var queryableList = new List<BrokenRule>(bb.BrokenRulesCollection);
    IEnumerable<BrokenRule> result;
    if (!string.IsNullOrEmpty(property))
    {
        result = from brokenRule in queryableList
                 where brokenRule.Property.Equals(property)
                 select brokenRule;
    }
    else
    {
        result = queryableList;
    }
    return result;
}

The code example here displays an extension method for BusinessBase that loops through the total collection of broken rules using a LINQ query that filters the broken rules for the selected property (using the property’s name). This method is very useful and powerful example of how developers can tweak the functionality of framework classes. It should come as no surprise that many more such extension methods will become available from the community soon for popular frameworks such as Microsoft’s Enterprise Library, nHibernate, ADF, CSLA and of course for the .NET framework itself.

Handle with care

Extension methods are a language feature that does not really stand out in the crowd, but can be very useful, especially to avoid repetitive work that should have been a feature of frameworks you apply to your projects. However, when developing extension methods you will need to be very aware of the side effects described above. I therefore recommend to implement extension methods sparingly. Under normal circumstances, you will still extend existing types by inheriting from them, even though this requires your developers to use your new class by convention instead of an extended base class. To leave you with a proper quote: “Creativity is a natural extension of our enthusiasm.”

The days are just packed. My talks in May and June 2009

The months May and June are notorious for the number of talks – as Rick van der Lans describes: May and June are speaker’s season. Just to remind me not to forget any of my upcoming talks, here’s a list:

  • May 12. Project estimation with smart use cases. At Capgemini, Utrecht. Presentation at internal software estimation seminar for Community of Practice Methods & Tools.
  • May 13. Achieving business flexibility with smart use cases. Keynote at seminar on  business flexibility at Synobsis, Castle Lage Vuursche, Baarn. See www.synobsys.nl.
  • May 14. Estimating with smart use cases. Half-day seminar for Array Seminars, NBC Nieuwegein. See www.arrayseminars.nl.
  • May 25. An introduction to smart use cases. Presentation at Capgemini event for large customer, Utrecht.
  • May 26. Agile requirements and smart use cases. Half-day presentation at Capgemini BAS, Apeldoorn.
  • May 28. Navigating through the hypes. Software architectures and patterns to help avoiding your projects to crash. Interactive talk on frameworks and how they can kill your projects at Microsoft DevDays, Congrescentrum Den Haag. See www.devdays.nl.

DSC_6268

  • June 3. Agile software development in everyday practice. Full-day seminar on doing agile projects for IT Works, Hotel Pullman, Diegem, Belgium. With guest speaker Stefaan van Royen, Mediamine. See www.itworks.be.
  • June 9. Pragmatic .Net development. Full-day seminar on software architectures and patterns for .Net software development for Array Seminars, .NBC Nieuwegein. See www.arrayseminars.nl.
  • June 15 & 16. Smart use cases from front to back. Custom two-day interactive workshop for information and business analysts of large Capgemini client at Capgemini Papendorp, Utrecht. Includes introduction of smart use cases, estimating smart use cases, smart use cases in service oriented architecture, testing smart use cases, domain driven design, agile, Smart / Scrum.
  • June 18. Mission impossible? Introducing agile in service oriented SAP projects. Talk at Integrate Agile Conference with Twan van den Broek, Topforce, for the Agile Consortium Benelux, Claus, Badhoevedorp. I didn’t notice that I have a double booking until now… trying to solve it.
  • June 18 & 19. Pragmatic modeling using UML and beyond. Fully packed two-day workshop on UML, modeling, smart use cases, requirements, domain driven design, model driven development and modeling in agile projects for IT Works, Hotel Crowne Plaza, Antwerp, Belgium. See www.itworks.be.
  • June 26. Agile anti-patterns. Yes, your agile projects can fail too. Entertaining talk on how to make your agile and Scrum projects fail, at the SDN Event in Hotel Houten, Houten. www.sdn.nl