NMoneys 3.1.0.0

on Wednesday, 2 January 2013

Happy New Year to everyone. This “long” silence has given me a bunch of ideas to write about that, by the “magic” of Resolutions will, hopefully, turn into a higher number of entries this year. Enough of it. Let’s talk about NMoneys.

What’s in for the user

Amendments

Being “small” and focused allows a project to move faster. That means we are able to include the latest changes and deploy them almost overnight. In this case, the Amendment 154 for the ISO 4217 states that from the 1st of January, the currency ZMK with numeric code 894 will become obsolete by the ZMV with currency 967. Said and done, having a method to obsolete currencies makes it possible for users that might be interested in the change, to have it right on time.

Documentation

Although I believe that the API of the library is small and pleasant enough to use and discover, I am aware of people that love browsing a tree of features (heck, I do something similar myself when decompiling assemblies).

The library has had API documentation ready to be consumed by Intellisense since day one, so it should be easy enough to turn it into MSDN/Visual Studio-style documentation, right? Wrong. It is embarrassing that there is no standard way to achieve such a thing. And no, going though the pain of installing and configuring Sandcastle (or the even less appealingly named SHFB) does not count, it does not.

I will be writing about the process in another post, but as a result of my findings, people can consume 90’s-styled-CHM documentation included in the all the Nuget packages: NMoneys, NMoneys.Exchange and NMoneys.Serialization.Json_NET.

What is not for the average user

The build system for NMoneys was simple enough and based on MSBuild. It worked but…
Why MSBuild? Because it comes out of the box with every .NET installation.
Was it pretty? No, it was not. It was horrible, indeed. It was all my fault. I have always been a NAnt guy that found MSBuild disgusting beyond any desire to learn it.
Did you jump the Ruby wagon? No, taking a dependency on Ruby is too big of a barrier for building such a small .NET project.
What, then?

One of the reason of adopting MSBuild was that is out-of-the-box. That is also the case with Powershell (sorry, Mono developers out there), so PSake is the chosen one. I will be writing about psake more in future posts; but, for the developer that wants to run the build it is as simple as it was before:

  1. open a Powershell prompt
  2. execute an script that will bootstrap psake and runs the build process

Isn’t it about time…

…that you go and download it from the usual Google code’s Downloads, Nuget’s Gallery?

A class that is not there

on Sunday, 14 October 2012

Sometimes one feels like jumping overboard a bit. Just for fun. And if it does not hurt anybody, why not?

The topic of today’s jump is: I do not feel like creating a class. Am I completely crazy? Did I finally stop programming? No. And no, but you wish I had Smile with tongue out

The scenario is simple: an API layer, a bunch of services which request objects inherit from an interface that defines a handful of properties and the need of an implementation of that interface outside the context of the API.

I could have gone and created a class that implements the interface and be done with it. But a Friday is a day to do different things.

I had read about Clay and how it makes easier create dynamic objects and even shape them into typed interfaces. But when I installed its NuGet package, I did not feel at easy taking a transitive dependency on Castle.DynamicProxy.

What can I do? Would I fold and create a class myself? Never. Not in a Friday.

And then my neurons helped me out by remembering that I had read about another project, impromptu-interface, that might help me doing what I intended: exchange the 5 seconds of creating a class that implements an existing interface for a bit of Friday fun.

And it worked! With no dependencies.

void Main()
{
    var walksLikeAFoo = new
    {
        I = 2,
        S = "string",
        D = 5m
    };
    
    IFoo itsAFoo = walksLikeAFoo.ActLike<IFoo>();    
    itsAFoo.Dump();
}

public interface IFoo
{
    int I { get; set; }
    string S { get; set; }
    decimal D { get; set; }
}

NOTE: Now I can go back to do some more meaningful work with a smile on my face and the sense of achievement of having benefited from someone else’s code.

Getting the hold on dynamic

It has to be clear that I am none of an early adopter when it comes to new technologies. Not so long ago I described my joy of discovering a use of optional and named arguments. Now is the time of dynamic.

Plumbing-less

Ok, you got me, I had used dynamic before, for example, when using Nancy to access route data or when parsing JSON data returned by EasyHttp. But that was using someone else dynamic APIs not designing mine.

My usage also bridges the gap between a dynamic reality and the static world of C#. That reality corresponds to localizable messages in web pages.
Localization can be resolved in many ways. When using resource files embedded in assemblies, Visual Studio creates the plumbing code to be able to access resource messages in .rex files through a static type. Since we chose to persist our resources inside a database we get no help from Visual Studio and were not in the mood to create a code generator to be able to write something like resources.name_of_resource when resources are needed outside a web page (where <%$Resources:resourceGroup, name_of_resource %> syntax is used).

Of course, we can do the good old resourceProvidedFactory.GetResource(“resourceGroup”, “resource”), but, let’s face it, now we can do better than that with very little effort:

Create a class that inherits from DynamicObject:

public class DynamicMessage : DynamicObject
{
    private static string getResource(string resource)
    {
        return ResourceLoaderFactory.Current.GetResource("resourceGroup", resource);
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = getResource(binder.Name);
        return true;
    }
}

That piece of code defers all member invocations (properties, fields) to the TryGetMembers() method. Which will delegate on the existing resource infrastructure to get a localized message. And we can use it simply by:

dynamic resources = new DynamicMessage();
string resource = resources.name_of_resource;

Done. A class less than 10 lines of code and we can go home. Thanks, dynamic, I do not always like you, but I appreciate when you make things easy for syntactic cuteness.

Neat uses of Optional Arguments in C#

on Saturday, 25 August 2012

I have been using .NET 4 for a while now but I have to admit I never thought well of optional arguments. My impressions gravitated between

  1. method overloading for lazy people
  2. hiding hideously designed APIS (Office COM Automation, I am looking at you!)

And so I have not used the feature extensively. But during the last week I have found a couple of usages that I can label as “useful”. Let me tell you about them:

Replace property initializers with descriptive constructors

Property initializers are cool. A bit verbose, due to curly bracing, but cool. Have properties with sensible names and you have a very descriptive and flexible way of creating objects. Perhaps too flexible. No one enforces you a minimum set (unless places in a constructor) and it is easy to forget setting a property.

Problem is, that if you have a long parameter list it is really easy to loose overview and what is which. Furthermore, have more than two properties with the same type together and you are likely to make mistakes (is latitude the first one, or is it longitude?).

Can’t I have my cake and eat it too? Yes, but please, share.

Imagine a class that has loads of properties (all cohesive, before you ask Winking smile):

public class IHaveQuiteAFewProperties
{
    public int I1 { get; set; }
    public int I2 { get; set; }
    public string S { get; set; }
    public decimal D1 { get; set; }
    public decimal D2 { get; set; }

    public IHaveQuiteAFewProperties() { }
}

Use very expressive property initializers and forget something:

var subject = new IHaveQuiteAFewProperties
{
    I1 = 1, I2 = 2,
    S = "something",
    // snaps! I forgot to set D1 to -3.5m,
    D2 = -4.3m
};

But, with a constructor that sets all properties...

public IHaveQuiteAFewProperties(int i1, int i2, string s, decimal d1, decimal d2)
{
    I1 = i1;
    I2 = i2;
    S = s;
    D1 = d1;
    D2 = d2;
}

...one can happily create an object, forget nothing and be expressive about what every argument means:

var subject = new IHaveQuiteAFewProperties(
    i1: 1, i2: 2,
    s: "something",
    d1: -3.5m, d2: -4.3m);

Specify just the argument that changes

Another case I recently found where they can dramatically improve readability is, not surprisingly, when one wants to override the default value Smile with tongue out

Let’s imagine we have a simple object that contains some collections:

public class CollectionOfCollections
{
    public string[] CollectionOne { get; set; }
    public string[] CollectionTwo { get; set; }
    public string[] CollectionThree { get; set; }
    public string[] CollectionFour { get; set; }
}

While testing a piece of code that creates an instance of this CollectionOfCollections in a way that only one of the collections is populated with a certain number of elements, while the other collections are to remain empty. One way of achieving it is asserting on each of the properties. I think that with very little work we can do much better:

[Test]
public void WhenBuildingComplexCollectionOfCollections_OnlyOneOfTheCollectionsIsPopulated()
{
    var subject = new CollectionBuilder();
    CollectionOfCollections result = subject.BuildWithComplexLogic();
    Assert.That(result, withMemberCount(two: 2));
}

What is inside this withMemberCount() method?
A simple default nullable argument that gets translated either into a collection length constraint or to an empty collection constraint for each one of the collections.

private static Constraint withMemberCount(uint? one = null, uint? two = null, uint? three = null, uint? four = null)
{
    return new LambdaPropertyConstraint<CollectionOfCollections>(b => b.CollectionOne, lengthOrEmpty(one)) &
        new LambdaPropertyConstraint<CollectionOfCollections>(b => b.CollectionTwo, lengthOrEmpty(two)) &
        new LambdaPropertyConstraint<CollectionOfCollections>(b => b.CollectionThree, lengthOrEmpty(three)) &
        new LambdaPropertyConstraint<CollectionOfCollections>(b => b.CollectionFour, lengthOrEmpty(four));
}

private static Constraint lengthOrEmpty(uint? length)
{
    return length.HasValue ?
        Has.Length.EqualTo(length.Value) :
        (Constraint)Is.Empty;
}

Neat is not enough. One starts to reap the benefits really soon when several tests are written and each one asserts a different count on different collections.

NOTE: LambdaPropertyConstraint<> is a typed counterpart to the out-of-the-box in NUnit’s PropertyConstraint that allows passing further constraints to be applied to the member. It is part of Testing.Commons.NUnit.

Is Agile a Scam?

on Wednesday, 1 August 2012

Yesterday, I bumped into an article that mentions a report published by a supposedly reputed analysis firm (and I wonder what sort of company that is, anyway) in which data from a study is interpreted, implying a conclusion which does not leave “Agile” is a good position.

Unfortunately, it is only available to subscribers, so the information I was able to grasp is second-hand one. If that second-hand information is any accurate in its quotes of the original report I feel more than fine not giving my money to such sort of company; if it isn’t accurate, well, it is law-less Internet anyway…
Even if I touch briefly on the report itself, I ask the reader to take the time to read the summary, its comments and the comment from the leading article; they are enlightening, amusing and infuriating in balanced proportions.

On Generalizing

I consider “Agile” like a tag. A fuzzy, generic tab. Like “Haute Cuisine”, “Prêt-à-Porter” or any other French catchy phrase that one can think of that represents a general style, a product or technique that adheres to some very general principles.
Such tags are surprisingly easy to stick, mind you, and drawing conclusions over such concepts can lead to absurdities such as “Seal fur Prêt-à-Porter does not work too well for eskimos Inuit people” or “Haute Cuisine junk food is a failure, give me a greasy bum anytime”.

Conducting a survey on such an abstract and broad topic, on a very small segment (more than 200 practitioners? How many is more than X, anyway? X + 1? 157000 times X?) and writing a paper trying to draw conclusion and charge for it is shocking.
Most importantly, if the conclusions are of the type “Agile is not for everyone”, “Agile is hard” or “Agile works better only when implemented in smaller projects where the team is highly qualified and third party dependencies are minimal” we are better off interleaving witty conclusions such as “I did Agile for a while and my wife left me” to at least give the reader a laugh.
Or better yet, write a series of articles, substituting the keyword by any other. I volunteer to write “The Waterfall Dilemma”, “The Plumbing Dilemma” or “The Walking-Backwards Dilemma” drawing exactly the same conclusions (keywords aside) after asking random members of my family and cash the check, thank you very much.

What is Agile anyway?

If referred to Software Development, one can refer to the apparently outdated Agile Manifesto and be disappointed by its vagueness (as if Ten Commandments were detailed or complete). Or one can read several books about the maybe dozens of methodologies applying agile principles and good luck coming with a less than twenty paragraph definition.
I will stick with:

“A manifesto print-out on the wall plus applying software engineering practices to an iterative delivery process with continuous feedback from the real customer and capable and professional team members inside a high-bandwidth communication network. Take away any of the previous elements are you are asking for trouble”.

  • The print-out: well, one can live without it, but it is better is your have it at hand to remind you what we are doing the hard work for
  • Software Engineering practices: Instead, let’s write crappy code, without change control, not knowing whether it kind-of-works, switching knobs all over the only environment (production, preferably) you will ever need… And see how that works out for your success, shall we?
  • Iterative Delivery Process: or wait until 5 min to deadline to tell the bad news that the production server is not even in the data-center
  • Continuous Customer Feedback: or kill the fun to surprise the paying customer with a new color scheme for the application he did not ask you to build
  • Capable and Professional Team: or give me any hobo off the streets that can spell C-E-S-A-R. The methodology will provide…
  • High-Bandwidth Communication: which version of jQuery? I thought I was writing XAML! Back to the white-board.

Some misconceptions

Agile is glorified Time and Materials

The iterative nature of Agile methodologies makes it hard to shoe-horn fixed price. Tough getting it right; not worthy in my opinion. Does that mean you have free hand to screw your way around and being paid for your mistakes? Well, not really.
Your job as a software developer is develop the software your customer wants, not any other software. That involves interacting with the customer to find out what does he want, challenge him, delivering kick-ass software and show it as soon as possible so that it does not cost the customer an arm and a leg the very useful feature that the test user identified while exploring the software.
Develop unwanted software? Fail. Develop crappy wanted software? Laugh now, cry later. Show something in 6 months? Waste 6 months of customer’s money when he tells you he’d be better off with a desktop application.

Agile is Hard

Not really. Good Agile is hard. Lame Agile is surprisingly easy. Do the same as whatever you where doing before, change no organization or practice because someone complains it is tougher than before and call it something else. Voilà.
And do not forget to blame that expensive coach you brought for a week. Oh wait, he was not that expensive. As a matter of fact he was the cheapest you could find. In reality, he was not a coach, he was someone that your poker buddy met at a strip-club that watched a video on the Internet. It does not matter, though; you paid no attention to anything he said anyway and even if you did, your customer is not going to attend that hippy weekly meeting.

You know what is really, really hard? Professional bakery. The getting up early, tweaking those formulas because the flour served last week is different, investing in modern furnaces, attending courses and listening to the complaints of the customers: why are unsalted baguettes so expensive, if you only have to take the salt away of the normal ones, right?

Agile is a Development Methodology

No, it is not. Is a set of principles that establish a framework in which Software Development is more likely to succeed (in the experience of those who wrote the principles).
Oh, and neither is SCRUM. SCRUM is a project management methodology (and a fuzzy one, I must add). It can be applied to software projects, construction or even parenting. Implement SCRUM and poor practices in any of those areas and you are bound to fail. SCRUM will only make more apparent to everyone earlier in the process of failing.

Agile === No Documentation

That myth might come from the poor wording on the Manifesto: X over Y does not mean “DO NOT do Y”. It should be read as “if you are doing more Y than X, you are more likely to fail. I warned you”.
It happens that documentation is a specially obnoxious task that looses value as fast as isotopes disintegrate. It is like flossing, but taking significantly less effort and having significantly longer durability. And flossing is actually good for you.

Agile == Religion

It is never wrong, there are counter examples that prove otherwise and everything boils down to the people practicing it.
Yup, they are exactly the same. Let’s leave it just right there, pal.

Agile is Developer-Centric

I would say, it is more like developer-fueled. It would be centric if the goal would be software. But, and this may shock many people, it is not, The goal is to satisfy a business need, or a scientific need or… Software is a tool. Everyone hates bad tools. Let tool makers build their tools. Good tools-makers know what they have to do for the tool to perform. And even better tool-makers listen and interact with tool users to improve the quality of the tool.
Remove the tool-user and the maker is out of business. Remove the maker and the user is banging nails with a bottle.

Agile Existence is Mercantilist

This is myth confirmed. Agile exists for the purpose of making money by selling books, services and courses; not for the good it may bring to society as a whole. We will have to wait for a change of government to get paid just for “inventing” concepts. Next rent is paid with a brilliant idea; wait for the laugh of my landlord.
Unfortunately I am forced to say the same about… well, everything out there in Capitalism. Ideas have very little value if they do not bring money home. Of course, no one is forcing you to buy books, services or courses. You may be compelled to invest on them if you think it will help you in your business.
I cannot imagine anyone writing “The Vacuum-Cleaner Dilemma” and concluding that one has to be reluctant of vacuum-cleaners because they are sold my companies willing to make money out of them instead of the work they save to the user. Now, would you buy the same vacuum-cleaner that works very well for your neighbor or would you, in a tight fisting attack, plunge for the purchase of something else that costs one fifth of the price? Think carefully your answer.

Agile is Only for Good People

Well, if you create software you better have damn good software developers, testers, managers and operation guys. Same with doctors, lawyers,…
Give bad tools to good professionals and they are worse off than good professionals with good tools.
Give a monkey a great tool such an smartphone and he’ll be disappointed at how bad it is at opening nuts.
Give a group of monkeys a book on table manners and they will struggle with the fish fork.
Isn’t it fun writing about truisms?

My Personal Take

I care naught about analysis companies. And I care less than that for those that imply that X exists for the sake of money, but fail to see the irony of writing such a statement in a paid paper.

Agile development (by my definition) works for me; apparently works for my company’s clients and I won’t stop investigating and refining ways to do my work better. And I’ll do it for personal pride and for a bigger check. And if and when something better comes in my way I will ditch Agile with no tears and cash more money while weeping loudly.

But please, let that Next-Big-Thing be applied by my extremely talented team of fellow developers, outstanding managers and open-minded clients. I have a feeling we might get lucky that time too.

A Refactoring Journey

on Friday, 13 July 2012

I have spent a week heavy on the refactoring side. It’s been a while since I spent so much time on a “virgin” codebase, growing it test first. And I want to share with you, guys and girls, a piece of refactoring that ended up being pretty cool.

Triangulate, always triangulate

I was happily developing one class at a time. But since the first class I felt an tingle. Like those lines drawn from Spiderman’s face. spidersenseThe tingle became an itch when, while developing a second class, I was doing pretty much the same thing. And the itch became a rash when, for the third time I did the same.
The thing in question, was performing one of two actions depending of the presence or absence of value of a pair of variables.

But everyone knows that you do not scratch when you have a rash. Right? RIGHT!? One does not go blindly hurting himself. In the case of code, one  does not endeavor refactoring quests without having a set of tests that make you confident that things will be as they were before and no new defects have been introduced. Right? RIGHT!?
In my case, I was going tests first, so I had a battery of tests for the classes that provoked the rash.

Moral of the story is: one should put up with a tingle, could put up with an itch and must act with the rash. Bringing “the big guns” for a tingle does not make sense and can be counter-productive.

Primitives are evil, value objects FTW

In reality they are not evil. They are very useful indeed, but their main feature (its generality) is usually their biggest disadvantage.
There are million of examples when primitive types are used for sheer laziness but, in reality, a custom value object communicates the concept way better.
For example: can one really perform all operations of a string on a conventional name? does that number represent meters or inches? probabilities bigger than one? These and other aberrations can (and do) happen when the concept is represented with a primitive type (a string, an integer or a floating point number).

In the case that occupies us, the two operations have a value object as a subject, although the value objects (which happen to be nullables) are created out of Nullable<T> primitive types.

public struct ValueObject_A
{
    public ValueObject_A(int a) : this()
    {
        Value = a;
    }
    public int? Value { get; private set; }
}
public struct ValueObject_B
{
    public ValueObject_B(decimal b) : this()
    {
        Value = b;
    }
    public decimal? Value { get; private set; }
}

The Choice

This choice value object have multiple but cohesive responsibilities:

  1. ensure that only one of the possibilities is active (not two, not zero)
  2. build the value object out of the valued primitive and nullify the other
  3. perform one out of two actions
public class AorB
{
    private ValueObject_A? A { get; set; }
    private ValueObject_B? B { get; set; }
    public AorB(int? a, decimal? b)
    {
        ensureOnlyOne(a, b);
        A = a.HasValue ? new ValueObject_A(a.Value) : default(ValueObject_A?);
        B = b.HasValue ? new ValueObject_B(b.Value) : default(ValueObject_B?);
    }
    private void ensureOnlyOne(int? a, decimal? b)
    {
        if ((a.HasValue && b.HasValue) || (!a.HasValue && !b.HasValue))
        {
            throw new NotSupportedException("Either A or B");
        }
    }
    public string Do(Func<ValueObject_A, string> actionWithA, Func<ValueObject_B, string> actionWithB)
    {
        return A.HasValue ? actionWithA(A.Value) : actionWithB(B.GetValueOrDefault());
    }
    public static AorB OnlyA(int a)
    {
        return new AorB(a, default(decimal?));
    }
    public static AorB OnlyB(decimal b)
    {
        return new AorB(default(int?), b);
    }
}

He chose… poorly

Or we could, instead.

One abstraction introduced, one abstraction that can be tested in a fraction of the time it takes to deploy the thing, fire up the complete application, exercise the feature, see it burn because you suck at boolean logic, attach the debugger,… you get the picture, right? RIGHT!?
Let’s check that the correct function is executed according to the presence of the value, and that the other function is not executed.

One can walk the anonymous method path, but will find it noisy with all those curly braces:

[Test]
public void Do_UseAnonymousMethods_ABitNoisy()
{
    var subject = AorB.OnlyA(3);
    Func<ValueObject_B, string> notExecuted = b =>
    {
        Assert.Fail("must not execute");
        return string.Empty;
    };
    bool wasExecuted = false;
    Func<ValueObject_A, string> executed = a =>
    {
        Assert.That(a.Value, Is.EqualTo(3));
        wasExecuted = true;
        return string.Empty;
    };
    subject.Do(executed, notExecuted);
    Assert.That(wasExecuted, Is.True);
}

One can step to remove noise by using methods as the functions, but we can see duplication coming:

[Test]
public void Do_UseMethodForNotExecutedFunc_LeadsToDuplication()
{
    var subject = AorB.OnlyB(3.5m);
    bool wasExecuted = false;
    Func<ValueObject_B, string> executed = a =>
    {
        Assert.That(a.Value, Is.EqualTo(3.5m));
        wasExecuted = true;
        return string.Empty;
    };
    subject.Do(notExecuted, executed);
    Assert.That(wasExecuted, Is.True);
}
private string notExecuted(ValueObject_A a)
{
    Assert.Fail("must not execute");
    return string.Empty;
}
// same old, same old
private string notExecuted(ValueObject_B b)
{
    Assert.Fail("must not execute");
    return string.Empty;
}

Duplication? Couldn’t that type of duplication be solved by using generics? I heard that they are not only for collections Winking smile

[Test]
public void Do_GenericForTheRescue_RemovesDuplication()
{
    var subject = AorB.OnlyA(3);
    bool wasExecuted = false;
    Func<ValueObject_A, string> executed = a =>
    {
        Assert.That(a.Value, Is.EqualTo(3));
        wasExecuted = true;
        return string.Empty;
    };
    subject.Do(executed, delegate(ValueObject_B b) { return notExecuted(b); });
    Assert.That(wasExecuted, Is.True);
}
private string notExecuted<T>(T aOrB)
{
    Assert.Fail("must not execute");
    return string.Empty;
}

But… wasn’t it about noise? Are you kidding me? An anonymous delegate syntax in 2012? Yeah, but if I show you the goodies from the beginning where’s the fun?

[Test]
public void Do_WithTypeInference_SlimAsItCanBe()
{
    var subject = AorB.OnlyB(3.5m);
    bool wasExecuted = false;
    Func<ValueObject_B, string> executed = a =>
    {
        Assert.That(a.Value, Is.EqualTo(3.5m));
        wasExecuted = true;
        return string.Empty;
    };
    subject.Do(notExecuted, executed);
    Assert.That(wasExecuted, Is.True);
}
private string notExecuted<T>(T aOrB)
{
    Assert.Fail("must not execute");
    return string.Empty;
}

And here we are, no duplication for the notExecuted() function and syntax clean as a whistle: subject.Do(notExecuted, executed). It may seem not much, but do I have to remind you that refactoring is an art of evolution without revolution?

The journey

  1. tingly code
  2. itchy code
  3. rash-y code
  4. rash-y code with tests
  5. introduce value objects A and B
  6. new abstraction AorB
  7. test abstraction
  8. use generics and type inference to test simple abstraction
  9. be amazed
  10. replace rashy-code with tested abstraction
  11. green lights everywhere
  12. party!

NMoneys. Bumped to 2.5

on Sunday, 8 July 2012

Why 2.5?

Previous to 2.5 came 2.2. But to highlight that changes between the two versions are pretty “dramatic” I chose to bump the version number. Fear not, not everything has been turned upside down.

Breaking changes

Everyone hate breaking changes.

  • Fellow developers hate them because they make their working applications stop working when the library is updated
  • Users hate them because it takes time for their application to be updated with “the next killer feature” and the developer is busy changing a bunch of broken unit tests
  • Business people hate them because they cost money and precious development hours
  • Author developers hate them because it is a sign that they did not thought the API through enough

But we cannot live in a world of infinite stability or being Microsoft to put up with rotten APIs. Environmental forces change and an author of a software library has one of three options:

  1. do not break it, even though we all know we were wrong
  2. offer an alternative API with the new design while we slowly deprecate the previous one
  3. suck it and assume you were wrong before (and risk being wrong again)

With NMoneys we have the luxury of not having a massive user base. Besides, our users are great fellows that understand that there are breaking changes and Breaking Changes (note the capitals).

The breaking change we are talking about could be one of the worst: changing an interface. A change like that usually means breaking custom implementations of that interface. A royal pain in the neck for the developers that took the steps to implement it.
In our case it is an extension point interface, meaning that we have provided some default canonical implementations of that interface, but allowing injection of custom behavior when that was needed. I chose to believe that there are not a lot of custom implementations of that interface lying around.

Furthermore, an interface change could mean than not only implementations break, but consumers of that interface might break as well (depending on whether the change affects interface’s return types).
In that extent, I choose to believe me lucky as well, for the damage is minimized by returning a type that somehow extends the previous return type (cursive extends as they are not substitutable, from inheritance point of view, only that the way of interacting with the type is pretty much the same).

Alright, enough justification, what is that breaking change everyone talks about?

The Change(s)

version 2.2 version 2.5
Money[] Money.Allocate(int) and Money[] Money.Allocated(int, IRemainderAllocator) Allocation Money.Allocate(int) and Allocation Money.Allocated(int, IRemainderAllocator) more
void Allocate(Money remainder, IList<decimal> alreadyAllocated); Allocation Allocate(Allocation allocationSoFar); more
NMoneys.Allocators NMoneys.Allocations more

Split allocation return type

In 2.2, a feature to calculate split allocations was added (Money.Allocate(int)). It returned an array of Money to represent the quantity allocated to each recipient. It turns out that using a primitive type (and array) is not enough (how many times have seen this?) to represent several situations, for instance: a quantity so small that cannot be allocated; or a quantity that can be evenly allocated, but it has some remainder that is itself too small to be distributed.

The solution is return something that can be used like an array (can be enumerated, indexed and its length interrogated), but communicates more information about the result of the allocation operation:

image

Interface change

And the interface change we talked about before is IRemainderAllocator. As I mentioned before, I do not expect many custom implementations of that interface; but comparing both signatures one has to conclude that we are much better off with the newer version.

Namespace change

Another breaking change is a namespace change. In 2.2 we only had implementations of IRemainderAllocator and the internal EvenAllocator, so it made sense to call it .Allocators. With the new features, new types and “surfaced types” it makes so much sense that everything allocation-related “lives” under .Allocations.

New Features

But sure a version bump deserves new features on top of breaking changes. And we indeed have more features.

Pro-Rated allocations

Undoubtedly the star feature of the release are pro-rated allocations. If previously we could allocate a certain quantity amongst n recipients evenly, now we are able to allocate it unevenly, that is, each recipient might get more or less of their even share depending of a ratio (a fraction between 0 and 1) passed to the operations. Such operation could help solve the mildly famous Foemmel’s Conundrum (or how to split 5 cents amongst two parties where the first one gets a 30% and the second the remaining 70%):

Money scarce = .05m.Usd();
var ratios = new RatioCollection(.3m, .7m);

Allocation allocated = scarce.Allocate(ratios);
Assert.That(allocated, Is.EqualTo(new[]
{
    .02m.Usd(),
    .03m.Usd()
}));

But that problem does not have only one solution, as it depends on the order in which remaning quantities are allocated:

Money scarce = .05m.Usd();
var ratios = new RatioCollection(.3m, .7m);

Allocation allocated = scarce.Allocate(ratios, RemainderAllocator.LastToFirst);
Assert.That(allocated, Is.EqualTo(new[]
{
    .01m.Usd(),
    .04m.Usd()
}));

Incomplete allocations

Besides try to do complete allocations one can now opt in for incomplete allocations, meaning that one can distribute just the fair amount of a quantity, to discard the remainder if one choses so:

Allocation unfair = new EvenAllocator(8.3m.Usd()).Allocate(4);

Assert.That(unfair, Is.EqualTo(new[] { 2.07m.Usd(), 2.07m.Usd(), 2.07m.Usd(), 2.07m.Usd() }));

Assert.That(unfair, Must.Be.Incomplete(a =>
{
    a.Allocated = 8.28m.Usd();
    a.Remainder = .02m.Usd();
}));

Words of Thank you

Just as I thanked Berryl Hesh for his contribution in 2.2 of split allocation, I have to thank him twice this time: one for the contribution of the pro-rated allocations feature and another one for being patient and assertive when I literally turned his code inside out to simplify the resulting code (I believe) from his contribution. Looking forward for that article.

An extra one comes to show me an interesting way of splitting tests of chunky classes (such as Money) into partial classes. We will be able to see more of those in further releases.

It ain’t going anywhere

So you can get the latest version in the usual Google code’s Downloads, Nuget’s Gallery or RubyGems.org.