Sunday, April 28, 2013

Customizing a knockout validation message

Knockout validation is a plugin that allows you to extend observables with validation. If you're familiar with jQuery validation, you will notice that most provided validation rules are very similar.

One of the validation rules available out-of-the-box is pattern validation. By default the error message for violating this rule doesn't mention the expected pattern. And in general, showing the expected pattern probably isn't a good idea since your users will have no idea what you're talking about. If you're building a back-end for devops purposes, it might be more acceptable though.

Instead of "Invalid.", I want my error message to be "I can't believe the pattern doesn't match {pattern}.".
test('1. When the object is invalid, the error message contains our formatted message.', 
    function () {
        var testObj = ko.observable('').extend({ pattern: 'myPattern' });    
            
        testObj('something');
        
        equal(
            testObj.error, 
            'I can\'t believe the pattern doesn\'t match \'myPattern\'.', 
            'The formatted error message is correct.');    
    }
);

Expected: "I can't believe the pattern doesn't match 'myPattern'."
Result:    "Invalid."
Diff: "I can't believe the pattern doesn't match 'myPattern'." "Invalid." 
Digging a bit into the source, I found the function that formats the error messages; it simply replaces {0} in the message with the params value.
formatMessage: function (message, params) {
    if (typeof (message) === 'function')
        return message(params);
    return message.replace(/\{0\}/gi, params);
};
So to change the error message to have it include the pattern, we can pass a pattern object which contains our message with the params placeholder and the params value. 
test('2. When the object is invalid, the error message contains our formatted message.', 
    function () {   
        var testObj = ko
            .observable('')
            .extend({ pattern: {
                message: 'I can\'t believe the pattern doesn\'t match \'{0}\'.',
                params: 'myPattern'
        }});                            
                
        testObj('something');
        
        equal(
            testObj.error, 
            'I can\'t believe the pattern doesn\'t match \'myPattern\'.', 
            'The formatted error message is correct.');    
    }
);

The formatted error message is correct.
Expected: "I can't believe the pattern doesn't match 'myPattern'."
This will make our test pass. It's not a great idea to repeat this in each location though. Since the plugin exposes its rules, you can just go in, modify the default message for the pattern rule, and see it applied everywhere.
test('3. When the objects are invalid, the error message contains our formatted message.', 
    function () {
        var testObj1 = ko.observable('').extend({ pattern: 'myPattern' });
        var testObj2 = ko.observable('').extend({ pattern: 'myPattern' });
                                            
        ko.validation.rules['pattern'].message = 
            'I can\'t believe the pattern doesn\'t match \'{0}\'.',    
        
        testObj1('something');
        testObj2('something');
        
        equal(
            testObj1.error, 
            'I can\'t believe the pattern doesn\'t match \'myPattern\'.', 
            'The formatted error message is correct for testObj1.');      
        equal(
            testObj2.error, 
            'I can\'t believe the pattern doesn\'t match \'myPattern\'.', 
            'The formatted error message is correct for testObj2.');      
    }
);

The formatted error message is correct.
Expected: "I can't believe the pattern doesn't match 'myPattern'."
The formatted error message is correct.
Expected: "I can't believe the pattern doesn't match 'myPattern'."
I hope that even if you weren't interested in this exact scenario, this post gave you an idea on how to go at customizing knockout validation messages. 

Sunday, April 21, 2013

Modeling the four-eye principle

Working in a financial domain over the last year, it was only a matter of time before I would be confronted with one of the variations of the two-man rule: the four-eye principle. Satisfying the principle is simple enough; an extra pair of eyes needs to approve of requested changes before they're applied to the system. This measure should prevent mistakes such as a user nuking North Korea by accident, or transferring all corporate funds to a personal off-shore bank account. In practice all you need is an accomplice.

Although I have seen artifacts of this concept, this is the first time I actively had to model it myself. Since I looked online for inspiration, but returned empty handed, I'm documenting my findings here.

I started out modeling the concept directly on the relevant entities, but it was obvious really soon that this was going nowhere. The solution headed in the wrong direction from the get go: copying records, dirty tracking, a bunch of possible states, resulting in complex transitions, and the need for an audit log. I couldn't even address these concerns without them bleeding into other layers such as queries and repositories. This design also failed to cover one edge scenario where we don't need an entity at all.

Returning home, I gave it another shot, but this time I modeled the principle as a separate concept, not touching any existing entities. A user hands in a request, which will be persisted, and will just sit there until a supervisor approves or declines it. If it's accepted, the request state gets updated, and all request handlers are invoked. It's the request handlers that are responsible for applying the requested change(s) to the system. Before the request handlers are invoked, no existing entities are touched.

Modeling the concept this way also leans closer to reality. You want to keep your core system as clean and simple as possible, to avoid confusion and mistakes where you can. If we would go back in time twenty years, the requests would also have lived in a separate drawer.

Here's some of my tinkering trying to support this concept.

A request is actually a template. It will always contain the current state, and some meta data concerning previous state transitions, but the actual content is generic. When a supervisor accepts or declines a request, a guard makes sure the user that made the original request, is not the one doing the supervision. Other guards make sure the status transition makes sense; you need to make a new request once it has been supervised. When the request is accepted, a domain event gets raised.
public class Request
{
    public Request(Requested requested, IRequestContent content)
    {
        Guard.ForEmpty(requested, "requested");
        Guard.ForEmpty(content, "content");

        Id = Guid.NewGuid();

        Requested = requested;
        Content = content;
        Status = Status.Waiting;
    }

    public Guid Id { get; private set; }

    public Requested Requested { get; private set; }

    public Supervised Supervised { get; private set; }

    public IRequestContent Content { get; private set; }

    public Status Status { get; private set; }

    public void Accept(Supervised supervised)
    {         
        ChangeStatus(Status.Accepted, supervised);

        DomainEvents.Raise(new RequestAcceptedEvent() { RequestId = Id });
    }

    public void Decline(Supervised supervised)
    {           
        ChangeStatus(Status.Declined, supervised);            
    }

    private void ChangeStatus(Status status, Supervised supervised)
    {
        Guard.ForEmpty(supervised, "supervised");
        Guard.SupervisingUserBeingTheRequestingUser(Requested.By, supervised.By);

        if (Status != Status.Waiting)
            throw new InvalidOperationException(
                "This request is already accepted or declined.");
        if (status == Status.Waiting)
            throw new InvalidOperationException(
                "The status shouldn't be changed to Waiting after creation.");            

        Status = status;
        Supervised = supervised;
    }

    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
            return false;

        var other = obj as Request;

        return Id == other.Id;
    }

    public override int GetHashCode()
    {
        return this.Id.GetHashCode();
    }
}  
An event handler listens for the request accepted event, and uses the content's type to make a generic type, which is then used to search the container for relevant request handlers. Since our type system isn't aware of our specific types - request handlers and request content are both objects at this point, I sprinkle some dynamic on top, and rely on the DLR to invoke the correct method. I think drawing outside the static lines here helps keeping things simple; it's definitely nicer to read than its counterpart, which needs to rely on reflection.
public interface IRequestHandler<TRequestContent>
{
    void OnAccepted(TRequestContent requestContent);
}

public class RequestAcceptedEventHandler : IEventHandler<RequestAcceptedEvent>
{
    private readonly IKernel _kernel;
    private readonly IRequestRepository _requestRepository;

    public RequestAcceptedEventHandler(IKernel kernel, IRequestRepository requestRepository)
    {
        _kernel = kernel;
        _requestRepository = requestRepository;
    }

    public void Handle(RequestAcceptedEvent @event)
    {
        var request = _requestRepository.GetById(@event.RequestId);

        var requestHandlerType = 
            typeof(IRequestHandler<>)
                .MakeGenericType(request.Content.GetType());
        foreach (var requestHandler in _kernel.GetAll(requestHandlerType))
            ((dynamic)requestHandler).OnAccepted((dynamic)request.Content);
    }
}
Now that we have this in place, a scenario where a user requests to have a missile launched, and a supervisor approves of this request, could look like this.
static void Main(string[] args)
{
    var repository = kernel.Get<IRequestRepository>();
    
    var launchMissileRequest = new Request(
        new Requested(new User("MiniMe")),
        new LaunchMissileRequestContent("V-2", "The Ozone Layer"));
    
    repository.Add(launchMissileRequest);

    ListRepositoryContent(repository);
    
    var request = repository.GetById(launchMissileRequest.Id);
    
    request.Accept(new Supervised(new User("DrEvil")));

    ListRepositoryContent(repository);

    Console.ReadLine();
}

public class LaunchMissileRequestHandler : IRequestHandler<LaunchMissileRequestContent>
{
    public void OnAccepted(LaunchMissileRequestContent requestContent)
    {    
        Console.WriteLine(string.Format("Launching {0} to {1}!!",
            requestContent.MissileName, requestContent.Destination));
    }
}

public class LaunchMissileRequestContent : IRequestContent
{
    public LaunchMissileRequestContent(string missileName, string destination)
    {
        Guard.ForEmpty(missileName, "missile name");
        Guard.ForEmpty(destination, "destination");

        MissileName = missileName;
        Destination = destination;
    }

    public string MissileName { get; set; }

    public string Destination { get; set; }

    public string Summary
    {
        get { return string.Format("Launch {0} to {1}.", MissileName, Destination); }
    }
}
This will result in the following being outputted to the console.
-----------------------------------------
Id: dcd6eaba-1a3e-4d81-82f4-4b2938911e7e
Status: Waiting
Summary: Launch V-2 to The Ozone Layer.
-----------------------------------------
Launching V-2 to The Ozone Layer!!
-----------------------------------------
Id: dcd6eaba-1a3e-4d81-82f4-4b2938911e7e
Status: Accepted
Summary: Launch V-2 to The Ozone Layer.
-----------------------------------------
Fully exposed

It's rare to see people share how they go at modeling real-life problems - money and withdrawing funds from an account don't count. And I get it; you're fully exposed; there is more than one way to skin a cat; history and context is lost in translation; and the devil is in the details. It's a shame though; there is no technology or methodology that will save you when you get these things catastrophically wrong.

The source of this article is up on GitHub. If you feel like toying with this concept, be my guest. Be gentle about it though. 

Sunday, April 14, 2013

Internationalization in NancyFx

When I'm building web applications for non-work projects, I still find myself using Nancy most of the time. Something I looked at this week was how I could get the user's culture in Nancy. I looked a bit at the latest source, and discovered that recently some work has been done in this area.

When you look at the Nancy context, available in modules, you will find a Culture property.
public SomeModule()
{
    Get["/"] = _  => {
        var cultureInfo = Context.Culture;

        return View["Home.cshtml"];
    };
}
Tracing through the source, you can see that this value is set in the default contextfactory, which in its turn queries a culture service. The service itself iterates over all culture conventions until it finds one that returns a value.
public CultureInfo DetermineCurrentCulture(NancyContext context)
{
    CultureInfo culture = null;

    foreach (var convention in this.cultureConventions)
    {
        culture = convention(context);
        if (culture != null)
        {
            break;
        }
    }

    return culture;
}
The default culture conventions make use of some built-in culture detection mechanisms. Six mechanisms are in place, and will be tried in a specific order.
conventions.CultureConventions = new List<Func<NancyContext, CultureInfo>>(6)
{
    BuiltInCultureConventions.FormCulture,
    BuiltInCultureConventions.PathCulture,
    BuiltInCultureConventions.HeaderCulture,
    BuiltInCultureConventions.SessionCulture,
    BuiltInCultureConventions.CookieCulture,
    BuiltInCultureConventions.ThreadCulture
};
  1. Form: does the form data contain a CurrentCulture entry?
  2. Path: is the first part of the url a culture?
  3. Header: is the Accept-Language header present?
  4. Session: is there a CurrentCulture key in the session?
  5. Cookie: is there a CurrentCulture key in the cookie?
  6. Thread: what's the current thread culture? 
So out-of-the-box Nancy is very smart about how she will try to determine a user's culture. You can either pass the culture to the relevant formatting functions, or you can set the culture for the execution of the whole request. 

The latter can be achieved with a before hook. You can add this to an individual module, or to each module in your application by adding it to the bootstapper.
protected override void RequestStartup(
    IKernel container, 
    IPipelines pipelines, 
    NancyContext context)
{
    base.RequestStartup(container, pipelines, context);

    pipelines.BeforeRequest += ctx =>
    {
        Thread.CurrentThread.CurrentCulture = context.Culture;

        return null;
    };
}
I posted this on the mailing list and GrumpyDev raised one concern; depending on in which host you're running Nancy, it might not be guaranteed that the whole request is executed on the same thread, so that could produce some undesired results. ASP.NET runs each request on its own thread though. 

Sunday, April 7, 2013

Designing entities: immutability first

The first year I wrote software for a living I spent my days mostly writing forms over data applications; most of my efforts were wasted just trying to make things work using ASP.NET and the Webforms engine. It was only after a year and graduating from the School of Hard Knocks that I learned there is a lot more to building clean and maintainable software than knowing the ins' and outs' of a proprietary UI technology.

One of the habits I have adapted over time, is designing new entities as immutable objects first, and to go from there. I believe this helps me to make more deliberate design decisions, leading to better designs.

Allow me to demonstrate this using a customer entity - I know this is cliché, but I have a hard time coming up with original examples.

A constructor

This one might sound rather obvious, but you would be surprised how many classes don't have the decency of a simple constructor, especially since C# introduced object initializers. While object initializers definitely look good, they make your code harder to maintain; classes don't communicate what they need to get by, nor do they get the opportunity to protect their invariants as early as possible.

Like I said, I design my classes to be immutable from the start; after initialization they can't be modified. I'm not even exposing any state for now.
public class Customer
{
    public Customer(
        Guid id,
        string firstName,
        string lastName,
        string street,
        string city,
        string country,
        DateTime birthdate,
        decimal balance)
    {
        FirstName = firstName;
        LastName = lastName;
        Street = street;
        City = city;
        Country = country;
        BirthDate = birthdate;
        Balance = balance;
    }

    public Guid Id { get; private set; }

    private string FirstName { get; set; }

    private string LastName { get; set; }

    private string Street { get; set; }

    private string City { get; set; }

    private string Country { get; set; }

    private DateTime BirthDate { get; set; }

    private decimal Balance { get; set; }
}
Comparing identities

An entity is always unique within a system; it has an identity. To encapsulate comparing two entities, and to avoid repeating myself, I always override the Equals and GetHashCode methods. We're not guided into doing this by our object's immutability though, but by common sense.
public override bool Equals(object obj)
{
    if (obj == null || GetType() != obj.GetType())
        return false;            

    var other = obj as Customer;
       
    return Id == other.Id;
}

public override int GetHashCode()
{
    return this.Id.GetHashCode();
}
Defaults

When a new customer is created, its balance is still empty. The constructor is the perfect place to initialize this default.
public Customer(
    Guid id,
    string firstName,
    string lastName,
    string street,
    string city,
    string country,
    DateTime birthdate)
{
    FirstName = firstName;
    LastName = lastName;
    Street = street;
    City = city;
    Country = country;
    BirthDate = birthdate;
    Balance = 0;
}
Protecting invariants

The next thing I'll do is use the constructor to guard for arguments that don't satisfy my objects invariants. This way we guarantee that the object can never be initialized with an invalid state; avoiding a bunch of trouble along the way.

We expect a customer to have a first name, last name, street, city and country which isn't empty. We also expect its birth date not to be in the future.
public Customer(
    Guid id,
    string firstName,
    string lastName,
    string street,
    string city,
    string country,
    DateTime birthdate)
{
    Guard.ForNullOrEmpty(firstName, "first name");
    Guard.ForNullOrEmpty(lastName, "last name");
    Guard.ForNullOrEmpty(street, "street");
    Guard.ForNullOrEmpty(city, "city");
    Guard.ForNullOrEmpty(country, "country");
    Guard.ForDatesInTheFuture(birthdate, "birthdate");

    Id = id;
    FirstName = firstName;
    LastName = lastName;
    Street = street;
    City = city;
    Country = country;
    BirthDate = birthdate;            
    Balance = 0;
}

public class Guard
{
    public static void ForNullOrEmpty(string value, string desc)
    {
        if (string.IsNullOrEmpty(value))
            throw new NullReferenceException(desc);
    }

    public static void ForDateInTheFuture(DateTime value, string desc)
    {
        if (value > DateTimeProvider.Now())
            throw new ArgumentException(
                string.Format("{0} can't be a date in the future.", desc))
    }
}
Composition and extracting value objects

I'm fairly confident that every self-respecting programmer is annoyed by the fact that the obvious concepts name and address haven't been extracted yet. Especially since that bloated constructor is all up in your face. Let's go ahead and extract two value objects: name and address.
public class Customer
{
    public Customer(
        Guid id,
        Name name,
        Address address,
        DateTime birthdate)
    {
        Guard.ForNull(name, "name");
        Guard.ForNull(address, "address");
        Guard.ForDateInTheFuture(birthdate, "birthdate");

        Id = id;
        Name = name;
        Address = address;
        Balance = 0;
    }

    public Guid Id { get; private set; }
    
    private Name Name { get; set; }

    private Address Address { get; set; }

    private DateTime BirthDate { get; set; }

    private decimal Balance { get; set; }
}

public class Name
{
    public Name(string first, string last)
    {
        Guard.ForNullOrEmpty(first, "first name");
        Guard.ForNullOrEmpty(last, "last name");

        First = first;
        Last = last;
    }

    private string First { get; set; }

    private string Last { get; set; }

    public string Full 
    {
        get
        {
            return string.Format("{0} {1}", First, Last);
        }
    }
    
    public override bool Equals(Object obj)
    {
        ...
    }
    
    public override int GetHashCode()
    {
        ...
    }
}

public class Address
{
    public Address(string street, string city, string country)
    {
        Guard.ForNullOrEmpty(street, "street");
        Guard.ForNullOrEmpty(city, "city");
        Guard.ForNullOrEmpty(country, "country");

        Street = street;
        City = city;
        Country = country;
    }

    private string Street { get; set; }

    private string City { get; set; }

    private string Country { get; set; }
    
    public override bool Equals(Object obj)
    {
        ...
    }
    
    public override int GetHashCode()
    {
        ...
    }
}
There, that looks better.

Tell, don't ask 

In good OOP we tell objects what to do, we don't want to query an object for its state and do something based on that; that would lead to broken encapsulation and thereby more brittle code.

Since our immutable object isn't exposing any state yet, we are forced to ask ourselves why we want to expose something. This way, disregarding "tell don't ask" becomes a deliberate choice.

Let's say we want to decrease the balance, and throw an exception when funds are insufficient. Instead of asking the customer instance and acting on that..
if (!customer.HasSufficientFunds())
    throw new InsufficientFundsException();
It's better to encapsulate data and behaviour, and tell it what to do instead.
public class Customer
{
    public Customer(
        Guid id,
        Name name,
        Address address,
        DateTime birthdate)
    {
        Guard.ForNull(name, "name");
        Guard.ForNull(address, "address");
        Guard.ForDateInTheFuture(birthdate, "birthdate");

        Id = id;
        Name = name;
        Address = address;
        Balance = 0;
    }

    public Guid Id { get; private set; }
    
    private Name Name { get; set; }

    private Address Address { get; set; }

    private DateTime BirthDate { get; set; }

    private decimal Balance { get; set; }

    private bool HasSufficientFunds(decimal value) 
    {
        return Balance - value >= 0;
    }

    public void DecreaseBalance(decimal value)
    {
        if (HasSufficientFunds(value))
            throw new InsufficientFundsException();

        Balance -= value;
    }
}
Making operations explicit

Next thing we want to do is change the address of a customer. Since we're not exposing the address property directly, we're also forced to think about a useful name for the operation; I decided to name it MoveTo. With this we make things more explicit, and thus more evident for people who are new to the domain.
public class Customer
{
    public Customer(
        Guid id,
        Name name,
        Address address,
        DateTime birthdate)
    {
        Guard.ForNull(name, "name");
        Guard.ForNull(address, "address");
        Guard.ForDateInTheFuture(birthdate, "birthdate");

        Id = id;
        Name = name;
        Address = address;
        Balance = 0;
    }

    public Guid Id { get; private set; }
    
    private Name Name { get; set; }

    private Address Address { get; set; }

    private DateTime BirthDate { get; set; }

    private decimal Balance { get; set; }

    ...

    public void MoveTo(Address newAddress)
    {
        Guard.ForNull(newAddress, "new address");

        Address = newAddress;
    }
}

var customer = new Customer(
    Guid.NewGuid(),
    new Name("Jef", "Claes"),
    new Address("Ergens", "Antwerp", "Belgium"),
    new DateTime(1987, 10, 18));

customer.MoveTo(new Address("Quelque part", "Brussels", "Belgium"));
Opening up bit by bit

In the meanwhile our entity is no longer immutable, but we're doing a good job of not exposing any state. If you're using the same model for reads as you do for writes, you're going to need to expose some properties eventually; for querying, but also for assertions. Make sure to only expose the getters though, and to avoid violating "Tell, don't ask" since that became a lot easier now.
public class Customer
{
    public Customer(
        Guid id,
        Name name,
        Address address,
        DateTime birthdate)
    {
        Guard.ForNull(name, "name");
        Guard.ForNull(address, "address");
        Guard.ForDateInTheFuture(birthdate, "birthdate");

        Id = id;
        Name = name;
        Address = address;
        Balance = 0;
    }

    public Guid Id { get; private set; }
    
    public Name Name { get; private set; }

    public Address Address { get; private set; }

    public DateTime BirthDate { get; private set; }

    private decimal Balance { get; set; }

    private bool HasSufficientFunds(decimal value) 
    {
        return Balance - value >= 0;
    }

    public void DecreaseBalance(decimal value)
    {
        if (HasSufficientFunds(value))
            throw new InsufficientFundsException();

        Balance -= value;
    }

    public void MoveTo(Address newAddress)
    {
        Guard.ForNull(newAddress, "new address");

        Address = newAddress;
    }
}
Summarized

By making my entities immutable from the start I am guided into adhering to a bunch of good practices:
  • A constructor
  • Comparing identities
  • Defaults
  • Protecting invariants
  • Composition and extracting value objects
  • Tell, don't ask 
  • Making operations explicit
  • Opening up bit by bit

I hope this post made some sense. I'd love to hear from you how I could improve this process, and which process you have accustomed yourself with over the years.