Specifying Business Rules by Example

One of the (many) benefits of using Specification by Example is that we get the business logic out in the open, being able to discuss it among developers, analysts, domain experts and users, instead of having it buried deep down in the code, wherefrom it can be rather hard to extract. And especially hard to extract non-manually.
 
But I think it is really hard and difficult to figure out from which perspective (some of) these business rules should be written. I mean, some business rules do belong in the abyss of the code, but other rules should most definitely be surfaced and be easy to extract as documentation.
 
To encourage some thoughts about this, I will describe my thoughts about a more general problem, which many systems will face. The problem, I think, is generic enough that the discussion it might spur will be useful in other situations.
 
We have some system (The System), which should be accessible by web (The Web Site) and mobile apps (The App). The System demands that Members do Create an Account. And for (more or less) obvious reasons The System has some requirements as to what makes up a Valid Username and a Valid Password.
 
I see the action of creating an account via The Website and The App as two different features (e.g. stories) of The System. So we would have two features for describing this, very much alike:
 
Feature: Create Account on The Web site
    As a potential Member of The System
    I want to Create an Account on The Web Site 
    so that I can login and use the features of The System.
Feature: Create Account via The App
    As a potential Member of The System 
    I want to Create an Account in The App 
    so that I can login and use the features of The System.

I believe I have managed to describe these two features in a way that open up for writing Scenarios suitable for automatic testing. A Scenario for the first Feature could be:

Scenario: Successfully Create Account on The Web Site
    Given a Valid Username that is not already in use and a Valid Password
    When The User asks The Web Site to Create the Account
    Then The Account is created by The System and the User is logged in as a Member of The System    

 

The Scenario for The App will be very much the same. And I figure that these Scenarios should be automatically tested through their corresponding UI.

 

My brain starts to heat up, though, when I think of the actual business requirements as to what makes up a Valid Username and a Valid Password. It should be obvious that these rules should be upheld no matter whether we create an account using The Web Site or The App. And since I will want the Create Account Scenarios above to be tested through UI, which is (very) slow, I don’t want to list several examples of Usernames and Passwords, which then all should be tested through the UI.

 

The App will (obviously?) use a Rest API for creating and accessing account information. The REST Api will use an Account Application Service, which also will be used by The Web Site’s server-side code (The Web Site could also use the REST Api AJAX-style, but for now we assume it doesn’t). Note, that this also means that we want to – somehow – test the REST Api, using the same business rules, which would result in one more Feature, describing that Scenario.

 

So what I’m actually aiming at here is that I want the Account Application Service to be Specified by Example, as well. And I want this because the rules that describe what constitutes a Valid Username and Valid Password are business rules, open for discussion. They should not be buried in the code. At the same time we don’t want to repeat the description of the business rules all over Features and Scenarios.

 

I cannot see a clear-cut way to this nicely and it may be that I’m using the wrong hammer (in this case SpecFlow, which may be hindering me thinking outside the famous box) for this or just my inexperience in Specification by Example shining through.

 

Since what I want to Specify is the Account Application Service I will call the users of the service for Consumers. What I have come up with is this:

 

Feature: Validate Username and Password
    As a potential Consumer of The System's Account Application Service 
    I want The Account Application Service to Validate my Username and Password according to the Business Rules.
    so that I can create an account with a Valid Username and Valid Password 

A Valid User Name:
  1. Cannot begin with white space.
  2. Cannot end with white space.
  3. Must start with a Unicode letter
  4. Must consist of letters, digits and spaces.
  5. Is case insensitive.
  6. Is at least 3 characters long.
  7. Is at most 30 characters long.

A Valid Password:
  1. Can contain any Unicode character.
  2. Is at least 6 characters long.
  3. Is at most 40 characters long.
  4. Must have at least 6 different characters.

 

The details of the business rules is not what’s at stake here. They should emerge out of the discussion of what is a Valid Username and Password, which is helped on the way by some examples:

 

Scenario Outline: Validating Username
    When I give a <username>
    Then The Account Application Service responds with an answer detailing whether the Username is <valid>.

    Examples: 
    | username:string                            | valid:bool |
    | user1                                      | yes        |
    | aVeryVeryLongUserNameWhichShouldBeAccepted | yes        |
    | æøåÆØÅ1234567890                           | yes        |
    |  user with space in beginning              | no         |

 

The examples here might not be that exhaustive, I’ve only discussed them with myself 😉 But the testing of this validation can be automated quite easily. And this will be the only Feature describing and testing the actual business rules regarding Valid Usernames and Passwords.

 

The Scenario Outline for Validating a Password would look just about the same. There should also be Scenario Outlines for Invalid Usernames and Passwords.

 

It is noteworthy, though, that the validation of Usernames and Passwords is not a User Story, it is – I think – more of an implementation detail. The same goes for the description of the REST Api.

 

For all the other tests (The Web Site, The App, REST Api) that need a Valid Username and Password (or invalid for that matter), it would be a good idea to have a TestHelper that supplies these, instead of dispersing the knowledge of Valid Usernames and Passwords over more tests than absolutely necessary.

 

I have chosen validation of Usernames and Passwords only as an example here. The business rules could have been anything else: financial rules, what ever. But where and how to describe the rules is still an issue.

Thoughts on usability

Designing software for ease of use is hard and as developers we seldom use our own software extensively when it has been delivered. But we are still expected to be able to put ourselves in the users seat and know how they work, to have the application work as seamlessly as possible and actually be a help in their work. This can be hard!

We are, however, not the only people in with this problem. To give some food for thought we can take a look on how ordinary house hold appliances work. I’m pretty certain that the typical developers of washing machines, tumblers, stoves and even to some extent TVs, are not the typical users of them at home.

Be aware of dangerous default settings.

I had a washing machine which, when turned on, had a default washing program where the temperature was 60 degrees (Celsius). If you weren’t aware of this you could easily ruin some clothes.

Don’t disable settings for no particular reason.

My current washing machine has a quick wash program, which takes 15 minutes on 30 degrees. But for some peculiar reason the machine can only sling the clothes at 1200 RPM instead of the maximum setting which normally is 1600 RPM. But on the quick wash program it is simply not possible to select higher than 1200 RPM. So in other words: I want my clothes washed in a hurry  but I have plenty of time to wait for it to dry?

Make sure that settings have obvious names.

My tumbler has two buttons, which – (probably inaccurately) translated from Danish – read: Delicate and Protect. And I cannot if my life depended on it remember what the difference between these two are. I’m sure at least one of them makes the tumbler dry the clothes with a lower temperature. But to figure out which one I have to look in the manual. Every time.

The user should be able to see what the application is doing.

My stove, which is a ceramic cooker, has some lights that indicate whether the cooking areas are “too hot” (to touch). But it has no indicator telling me whether any of the cooking areas are actually turned on – or off, for that matter. I have to manually inspect all the knobs to determine this.

Let the user multi-task if the scenario allows for it.

My LG TV has a Electronic Program Guide, which is fairly normal these days. But the brilliant designers has determined that I, when using the EPG, don’t want to listen to the program I was watching. The sound is disabled when I open the EPG. This seems like an odd decision (and it is very likely founded in something technical), since the sound would allow me to follow along in the program for some seconds, while reading up on what I’m actually watching 😉

 

These few examples show that we, simply by looking around, can spot usability problems. But how can we avoid them? Well, we will probably have to talk with our users about that… 😉

Serialization in one line

I have this neat static helper class, which makes it easy to serialize an instance of a class marked with [DataContract] and [DataMember]. E.g.

var xml = DataContractSerialization.Serialize(instance);

Where instance is an instance of any class which is serializable with DataContractSerializer.

Deserialization is equally easy:

var instance = DataContractSerialization.Deserialize(typeof(MyClass), xml);

or:

var instance = DataContractSerialization.Deserialize<MyClass>(xml);

The code for that class, which also can be found on GitHub:

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;

namespace SoftwarePassion.Common.Core.Serialization
{
    /// <summary>
    /// One-liners for the DataContractSerializer class.
    /// </summary>
    public static class DataContractSerialization
    {
        /// <summary>
        /// Serializes the specified value.
        /// </summary>
        /// <typeparam name="TType">The type of the value.</typeparam>
        /// <param name="value">The value.</param>
        /// <param name="knownTypes">The known types.</param>
        /// <returns>A string (xml) with the serialized value.</returns>
        public static string Serialize<TType>(TType value, params Type[] knownTypes)
        {
            if (knownTypes == null)
            {
                knownTypes = new Type[] { };
            }

            var serializer = new DataContractSerializer(typeof(TType), knownTypes);
            var stringBuilder = new StringBuilder(1024);
            using (var stream = XmlWriter.Create(stringBuilder))
            {
                serializer.WriteObject(stream, value);
                stream.Flush();
            }

            return stringBuilder.ToString();
        }

        /// <summary>
        /// Deserializes the specified XML into an instance of the given TType.
        /// </summary>
        /// <typeparam name="TType">The type of the data expected to have be serialized in the given xml.</typeparam>
        /// <param name="xml">The XML.</param>
        /// <param name="knownTypes">The known types.</param>
        /// <returns>A deserialized instance of the given TType.</returns>
        public static TType Deserialize<TType>(string xml, params Type[] knownTypes) where TType : class
        {
            if (string.IsNullOrEmpty(xml))
                return null;

            if (knownTypes == null)
            {
                knownTypes = new Type[] { };
            }

            var serializer = new DataContractSerializer(typeof(TType), knownTypes);

            using (var reader = new StringReader(xml))
            {
                var stream = XmlReader.Create(reader);
                return serializer.ReadObject(stream) as TType;
            }
        }

        /// <summary>
        /// Deserializes the specified XML into an instance of the given dataType.
        /// </summary>
        /// <param name="dataType">The type of the data expected to have be serialized in the given xml.</param>
        /// <param name="xml">The XML.</param>
        /// <param name="knownTypes">The known types.</param>
        /// <returns> A deserialized instance of the given dataType. </returns>
        public static object Deserialize(Type dataType, string xml, params Type[] knownTypes)
        {
            if (string.IsNullOrEmpty(xml))
                return null;

            if (knownTypes == null)
            {
                knownTypes = new Type[] { };
            }

            var serializer = new DataContractSerializer(dataType, knownTypes);

            using (var reader = new StringReader(xml))
            {
                var stream = XmlReader.Create(reader);
                return serializer.ReadObject(stream);
            }
        }
    }
}