Simple pattern matching in C#

08 November 2015

Nowadays, functional languages are becoming very popular. Few years ago we thought that the object orientation would be the answer for complexity in systems. But now, there is a belief that functional languages are the new solution. We will see what is gonna be the “thing” in the next years.

Lately, I had an occasion to apply one of feature from functional languages i.e pattern matching to code written in C#. But let’s start from the beginning.

Switch statement case study

Couple days ago, I encountered a piece of code which you can find below. It checks which hint is passed to the method. Then, it returns appropriate provider.

public IHintProvider GetHintProvider(string hint)
{
    switch (hint)
    {
        case HintOne:
            return new HintOneProvider();
        case HintTwo:
            return new HintTwoProvider();
        case HintThree:
            return new HintThreeProvider();
        case HintFour:
            return new HintFourProvider();
    }

    return new NullHintProvider();
}

It looks like a procedural code and I felt bad about the code, especially that I made it and probably forgot to refactor it. Nevertheless, it is not as worst as it could be, because for example it could have used the if and else if statements.

Table-driven methods

I started to look for better alternatives, whether I can refactor this slightly to reduce the switch statement noise. This led me to a table-driven method. I have known it before from Code Complete book. Basically it means, that sometimes we can precompute answers for given paths and store it in a table (or in our case in dictionary). Then, given an argument we just do lookup and return stored value. Owing to using this technique, we can now refactor GetHintProvider method:

private readonly IDictionary<string, IHintProvider> providers = new Dictionary<string, IHintProvider>
{
    {HintOne, new HintOneProvider()},
    {HintTwo, new HintTwoProvider()},
    {HintThree, new HintThreeProvider()},
    {HintFour, new HintFourProvider()}
};

public IHintProvider GetHintProvider(string hint) => 
	providers.ContainsKey(hint) ? providers[hint] : new NullHintProvider();

Simple pattern matching

But, as you can see the syntax of creating dictionary mimics somewhat the pattern matching feature from functional languages. I have been wondering if we are able to use this construction to create a simple pattern matching functionality in C#. It turns out, that C# compiler in some situations uses kinda duck-typing. If a type implements IEnumerable, we can use collection initializer while creating object instance of that type. Instances passed in collection initializer compiler translates to corresponding Add methods with matching signature. Given that, we can create Match class that stores patterns and associates code with them to execute when pattern matches. With that, we can write GetHintProvider method as following:

public IHintProvider GetHintProvider(string hint) =>
    new MatchFunc<string, IHintProvider>
    {
        {HintOne, s => new HintOneProvider()},
        {HintTwo, s => new HintTwoProvider()},
        {HintThree, s => new HintThreeProvider()},
        {HintFour, s => new HintFourProvider()},
        {Match.Default, s => new NullHintProvider() }
    }.Func(hint).Single();

Now, the code looks nice to me and it is more declarative than the original example.

If you are interested in, you can check code for MatchFunc class here.

Summary

Being declarative, expressing intent of code is an advantage of functional languages, that is presented as opposite to imperative code. Actually, I think code is easier to understand and to maintain. I’m curios whether C# language engineers have thought that its collection initializers syntactic sugar could be used in such a way. If not, it is interesting how the solution to problem in software field can be used in not foreseen ways later.

Creating decorator around large interface - from improvement to contribution

30 October 2015

Recently, I’ve caught myself that I was creating decorator around interface which has quite a few methods. I was interested only in one particular method, whereas for the others I had to delegate a call to the decoratee. Thus, it was tedious. This leads me to searching a way for doing this task automatically.

Apart from that, we could argue that the interface does not follow Integrace Segregation Principle as Robert C. Martin pointed out that >Clients should not be forced to depend upon methods that they do not use.

Unfortunately, we often work with code which we can’t change and that’s the case here.

Know your tools

I use ReSharper, so at the beginning I started to look if it can help with that. I started with the following code:

public class CachingRepository : IRepository
{
}

After couple minutes of investigation, I found that if code generation pop-up is invoked (Alt+Enter) there is an option Delegating members, but it is unavailable. So, I thought that maybe I should add to my class a field of interface type, which I want to decorate.

public class CachingRepository : IRepository
{
    private readonly IRepository repository;
}

After that step, the option Delegating members became available. Moreover, if caret position is on the class name and we press the shortcut for context actions (Ctrl+Enter), there is also an action Delegate implementation to ‘repository’ field available.

Visual Studio 2015, also offers quick actions, which are indicated by light bulb. We can invoke quick actions by using Ctrl+. shortcut. In earlier mentioned code snippet, if we put caret on interface name in type list of decorator, there would be actions offered by Visual Studio. One of the available fixes is Implement interface through ‘repository’, which produces the same results as the ReSharper code generation option.

More automation

I wondered why there is a requirement to include the field in class for the options to be available. After all, the field could be auto-generated. We can go even further and generate constructor with the decoratee as a parameter.

Let’s assume that we want to create a decorator around IRepository interface and we have:

public class CachingRepository : IRepository
{
}

Why can’t a tool do the work for us and generate following code?

public class CachingRepository : IRepository
{
    private readonly IRepository repository;

    public CachingRepository(IRepository repository)
    {
        if (repository == null)
        {
            throw new ArgumentNullException(nameof(repository));
         }
        this.repository = repository;
    }

    public void Save()
    {
        repository.Save();
    }

    public void Delete()
    {
        repository.Delete();
    }
}

Nowadays, thanks to Roslyn kind of task like that are much easier to implement. I thought about implementing it, but as I contribute to code-cracker project I came up with idea that this would be a good place to propose it as a new refactoring. Code-cracker is an analyzer library which provides helpful analysis and refactorings while you are writing C# (or VB) code. I created new issue in code-cracker project with details how the refactoring should work. Maybe someone else would be eager to implement it, unless I do it by myself.

Summary

I’m quite surprised, how the idea of adhering to the DRY principle turned into a contribution to the code-cracker project. In growing OSS world it is valuable to share your ideas because someone else might find it useful. We just need to find appropriate place where the idea could be used.

Testing for equality

26 October 2015

Often, while writing code we discover value objects in our application. Further, we also need to perform some operation on that types that involve determining equality of our value objects. In .NET there are established rules how to properly implement equality, but testing equality in value objects involves quite a lot of repetitive work. Let’s see what we can do with that and adhere to DRY principle. At first let’s review the rules that we should take into account while implementing equality.

Things you should remember while implementing equality

According to various resources, we should adhere to the properties of equality implementation, which are mentioned for example at MSDN.

So, the implementation of equality should:

  • be reflexive

x.Equals(x) returns true

  • be symmetric

x.Equals(y) == y.Equals(x)

  • be transitive

x.Equals(y) && y.Equals(z) == true then x.Equals(z) == true

  • be consistent

Invocations of x.Equals(y) return the same value as long as the values in x or y are not modified or references are not changed

  • return false when compared against null

x.Equals(null) == false

We should also override GetHashCode method when overriding Equals method, even compiler reminds us (as a warning) about that. This is due to implementation of many .NET classes (for example Hashtable or Dictionary), because they rely on the rule that if two objects are equal, they should return the same hash code value.

Nice, when you do it when implementing equality

There are also other guidelines which are good to use while implementing equality:

  • Overload == and != operator

As default the == and != operators perform identity check. When we provide our equality implementation we should also overload equality and inequality operators to avoid confusion and bugs while working with our objects.

  • Implement System.IEquatable<T> interface

This is an interface which defines a strongly typed Equals method, which can be used internally by other equality comparison methods. It is worth mentioning that using strongly typed Equals method avoids boxing while working with structs.

Test-Do list for testing equality

And last but not least, we must put logic for actually performing the equality comparison of our objects. Finally, this is our test-do list for testing equality implementation:

    [ ] Equals and GetHashCode method are overridden
    [ ] Check if implementation is reflexive
    [ ] Check if implementation is symmetric
    [ ] Check if implementation is transitive
    [ ] Check if implementation is consistent
    [ ] Check if returns false when compared to null
    [ ] Check whether implementation of equality works according to the comparison logic
    [ ] GetHashCode implementation produces correct results
    [ ] GetHashCode implementation is consistent
    [ ] == and != operators are overloaded
    [ ] == and != operators produce correct results
    [ ] IEquatable<T> is implemented
    [ ] IEquatable<T> produces correct results

Write once, run use everywhere

It is a lot of work, and our goal is to avoid repeating this every time we introduce value object. We know what to test for, to check equality implementation correctness. It would be the best if we can simply say what we want to test instead of how the equality tests should be done. That reminds me about the Write once, run everywhere slogan coined by Sun for Java. Actually, in our case we should say Write once, use everywhere. We can apply it here, write reusable component, which performs test cases and we can reuse it when we introduce new value objects to the system.

Fortunately, there is a library that can help us. It is AutoFixture (maybe there are other libraries but I don’t know any), and its part AutoFixture.Idioms. If we use that library, out of the box we can cross four items from test-do list. For the remaining items we can plug into AutoFixture.Idioms infrastructure and write assertions that performs other test cases.

So, this is the test-do list we have after using AutoFixture:

    [ ] Equals and GetHashCode method are overridden
    [x] Check if implementation is reflexive EqualsSelfAssertion class from AutoFixture.Idioms
    [ ] Check if implementation is symmetric
    [ ] Check if implementation is transitive
    [x] Check if implementation is consistent EqualsSuccessiveAssertion class from AutoFixture.Idioms
    [x] Check if returns false when compare to null EqualsNullAssertion class from AutoFixture.Idioms
    [ ] Check whether implementation of equality works according to the comparison logic
    [ ] GetHashCode implementation produces correct results
    [x] GetHashCode implementation is consistent GetHashCodeSuccessiveAssertion class from AutoFixture.Idioms
    [ ] == and != operators are overloaded
    [ ] == and != operators produce correct results
    [ ] IEquatable<T> is implemented
    [ ] IEquatable<T> produces correct results

For clarification, the assertions that will be presented are intended to use with immutable value objects. Data used in equality comparison is provided by arguments passed to constructor. Example of that value object is following:

public class Point
{
    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }

    public int X { get; private set; }
    public int Y { get; private set; }
}

Making EqualityOperatorOverloadAssertion

Goal of the EqualityOperatorOverloadAssertion is to check whether given type overloads == operator. Assertion derives from IdiomaticAssertion abstract class that is defined in AutoFixture.Idioms. IdiomaticAssertion provides helpful default implementation for methods from IIdiomaticAssertion interface. In our example we are overriding Verify method with Type parameter as this is the information necessary to perform interesting us assertion. After it turns out that type does not overload == operator, we throw meaningful exception which explains what is wrong. This is the code for EqualityOperatorOverloadAssertion:

public class EqualityOperatorOverloadAssertion : IdiomaticAssertion
{
	public override void Verify(Type type)
	{
		if (type == null)
		{
			throw new ArgumentNullException("type");
		}

		var equalityOperatorOverload = type.GetEqualityOperatorMethod();

		if (equalityOperatorOverload == null)
		{
			throw new EqualityOperatorException(
				string.Format("Expected type {0} to overload == operator with parameters of type {0}", type.Name));
		}
	}
}

Usage of EqualityOperatorOverloadAssertion:

[Fact]
public void ShouldOverloadEqualityOperator()
{
	new EqualityOperatorOverload().Verify(typeof(SomeValueObject));
}

I think that it doesn’t make sense to put here implementation of every assertion. Therefore, I decided to pick one simple assertion and explain how it is done. If you are interested how other assertions are implemented, please take a look here.

Compose all the assertions

To write a reusable component that will execute test cases from our test-do list we need to compose all created assertions. We can use CompositeIdiomaticAssertion class from AutoFixture.Idioms that allows to supply suite of assertions that will be verified.

public static class EqualityTestsFor<T> where T : class
{
	public static void Assert()
	{
		var fixture = new Fixture();
		var compositeAssertion =
			new CompositeIdiomaticAssertion(EqualityAssertions(fixture, new EqualityTestCaseProvider(fixture)));

		VerifyCompositeAssertion(compositeAssertion);
	}

	public static void Assert(Func<EqualityTestsConfiguration<T>> configuration)
	{
		var compositeAssertion =
			new CompositeIdiomaticAssertion(EqualityAssertions(new Fixture(), configuration()));

		VerifyCompositeAssertion(compositeAssertion);
	}

	private static void VerifyCompositeAssertion(CompositeIdiomaticAssertion compositeAssertion)
	{
		compositeAssertion.Verify(typeof(T));
		compositeAssertion.Verify(typeof(T).GetEqualsMethod());
		compositeAssertion.Verify(typeof(T).GetMethod("GetHashCode"));
	}

	private static IEnumerable<IdiomaticAssertion> EqualityAssertions(ISpecimenBuilder specimenBuilder,
		IEqualityTestCaseProvider equalityTestCaseProvider)
	{
		yield return new EqualsOverrideAssertion();
		yield return new GetHashCodeOverrideAssertion();
		yield return new EqualsSelfAssertion(specimenBuilder);
		yield return new EqualsSymmetricAssertion(specimenBuilder);
		yield return new EqualsTransitiveAssertion(specimenBuilder);
		yield return new EqualsSuccessiveAssertion(specimenBuilder);
		yield return new EqualsNullAssertion(specimenBuilder);
		yield return new EqualsValueCheckAssertion(equalityTestCaseProvider);
		yield return new GetHashCodeValueCheckAssertion(equalityTestCaseProvider);
		yield return new GetHashCodeSuccessiveAssertion(specimenBuilder);
		yield return new EqualityOperatorOverloadAssertion();
		yield return new InequalityOperatorOverloadAssertion();
		yield return new EqualityOperatorValueCheckAssertion(equalityTestCaseProvider);
		yield return new InequalityOperatorValueCheckAssertion(equalityTestCaseProvider);
		yield return new IEquatableImplementedAssertion();
		yield return new IEquatableValueCheckAssertion(equalityTestCaseProvider);
	}
}

If our value object is using only primitive types in constructor, we can rely on default equality test case provider that can handle this situation. It means, that we can write simple unit test for equality like:

[Fact]
public void ShouldImplementValueEquality()
{
	EqualityTestsFor<Point>.Assert();
}

But, if we need some more advanced scenarios, we can provide our own instances to describe what the results of equality test cases should be:

[Fact]
public void ShouldImplementValueEquality()
{
	EqualityTestsFor<Point>.Assert(
		() =>
			EqualityTestsConfigurer<Point>
			.Instance(new Point(1, 1))
				.ShouldBeEqualTo(new Point(1, 1))
				.ShouldNotBeEqualTo(new Point(1, 2))
				.ShouldNotBeEqualTo(new Point(2, 1)));
}

Wrap up

Checking equality implementation in value objects can be repetitive work, hence in this post you can find reusable approach to this problem. AutoFixture was used as a supporting library. It is heavily using role interfaces. Therefore it is very composable and it is a pleasure to work with design like that.

I’d like to add, if we spot in our solution that we are testing something more than once, it is a sign that maybe there is domain concept which should be made explicit. This is a somewhat term Test once, use everywhere. I find it useful, because it avoids duplication of the behavior in the system. We put behavior in one component, test it and we can use it everywhere. It also prevents us for combinatorial explosion of test cases when we have to test the same thing many times.

A few thoughts about Agile

13 October 2015

These days, Agile lightweight methodologies seem to be used as major software development methods across the world. Even not software development companies are using Agile processes. Scrum is one of the most common implementations of an Agile process. Recently, I’m thinking a lot about agile methodologies and it understanding after fourteen years when the Agile Manifesto came out and I want to share my thoughts. Before you read further, think about what is Agile for you?

Quick recall

The other software development process which is often contrasted to Agile methodologies is waterfall method. In waterfall process there were phases executed step by step. Input to the next stage was output from the previous. The assumption was, if we spend adequate amount of time on given phase and do it well, there will be no need for changes latter. For example, in design phase there was Big Design Up Front, and the argument was if we first design architecture of our system, therefore we don’t have to change anything in implementation phase. Unfortunately, that’s not true, because we can’t foreseen everything and in waterfall we can’t go back and change our design (at least easily). There wasn’t feedback of our design until the implementation phase was finished. That was the problem with waterfall process - lack of early feedback and difficulty in introducing changes. And that is what Agile changed - possibility of getting early feedback and responding to change even in lately development. The phases from waterfall are repeated in small time boxes and that defines iterative and incremental development. Because phases are repeated, therefore we have iterative development. New value to the software product is added feature by feature, therefore we have incremental development. Apart from that, you can see, that’s no surprise that other methods which gives us early feedback at different levels of creating software product are widely used. That’s why we use test-driven development, pair programming, code reviews and so on.

What you hear when you ask about Agile?

Probably when you ask somebody about Agile you will hear about sprint planning, board, cards, sprint retrospective and other artifacts and ceremonies connected with Scrum (because is the most common implementation of Agile). But they are implementation details. And like when we write code if we focus our system too much on implementation details it makes the system tightly coupled. The same I think focusing too much on implementation details prevent us for understanding what agile is aim for.

Introducing an Agile process into company means that you want to collect feedback early and therefore you welcome changes. But what if at the down level the change is hard to implement? You are agile because you write tasks on cards, estimate it and stick to the board or have daily standups? I’ve seen teams that doesn’t use neither Scrum nor any of the known agile frameworks but their code really embrace change. So, you would say they aren’t agile?

I think in the jungle of Scrum ceremonies and artifacts (or maybe not properly understanding what Agile aims for) we forgot about other principles that are behind Agile Manifesto. How many times did you see a piece of code that wasn’t good enough and you did nothing about that? The phrase I don’t have time is a poor explanation for professional software developer. We should be responsible for the code that we work on. If we make our code adaptive to change, but have problems with our software management process it’s still better than otherwise.

Leave the code better than you found it. (The Boy Scout Rule)

Yes, that’s important part of being agile. Carrying over the quality of the software product. And if you wonder how you would know that your change would not mess in other parts of the system. The answer is that you didn’t understand Agile idea well, you didn’t build your feedback foundation at the code level - you fooled yourself that the artifacts and events is all what you need to claim that you are agile.

Thank you Scrum inventors!

I’m not saying the Scrum or other Agile method is unnecessary. It is very helpful and we only could be thankful to inventors of the Scrum framework. But we must also understand that the codebase and it’s quality is a huge part of that how the software product is agile (even more bigger part than the process itself). You may listen to as many podcasts about Agile as you want, go to conferences and hear about best Agile practices but that is a waste of time until you build your feedback foundation and make your codebase adaptive to change.

Summary

To wrap up the Agile is more about feedback and embracing changing requirements than particular artifacts and ceremonies. If you find something interesting in this post, let everybody know, otherwise forget about it.