Wednesday, 9 October 2013

Design for errors #1: Immutable classes

There is only one thing in being a programmer that you can be sure of: you will make errors. There is no need for denying it, no matter how good you are, or how good you think you are. Not all mistakes can be detected during code review, unit or integration testing.

My proposition for dealing with this is: design for errors!

What does this mean? Make errors easy to spot and easy to fix. This can be done if you use SOLID principles in development. I would like to add some ideas of my own. Today I will start with first one (loved by functional programmers):

Create immutable classes

Immutable means: does not change after creation. Immutable class in C++ can only set its fields in constructor. No other method is allowed to change state of it (so all methods are declared const). Immutable class should not have any virtual method.

This has one big advantage over normal classes: you are 100% sure that no code is changing created value and you can use it everywhere without worrying about its state.

Look at OAuthParameters class in Kadu source code. It has only one of required properties: it does no have any virtual methods. But it has a lot of setters that change its state. We see in the code that these setters are all used just after object construction, so a Builder pattern should be used for creating instances of this class. There is also a mysterious sign() method. It has very bad property of changing state of this object from unsigned to signed - this state is hidden and not exposed by API in any place. Solution for this would be to make a new class, OAuthSignedParameters that can be created from OAuthParameters by new const method signed() or by some external class.

When all of this is done there will be two separate immutable classes (that are easy to reason about and really error-proof) that have strictly defined relationship. All methods that now require signed version of OAuthParameters will make this clear by requesting OAuthSignedParameters directly. A few types of errors go away with this rather simple change.

That's all for today.

No comments:

Post a Comment