jeudi 17 mai 2018

Bug generator: Non constrained construction


A bug generator is a style of code that is likely to contain bugs or produce bugs in the future as the code is extended by making them more likely. This is of course an anti-pattern. There are corresponding Prevention Patterns, basically less error-prone alternatives. Now that the term is defined, lets dive into today's bug generator, namely non constrained construction.


Non constrained construction means that it is possible to construct an invalid object. Examples are 1) mandatory parameters are set after construction using a setter 2) No validations in the constructor, for instance instantiating a PhoneNumber using any string. 3) Several parameters of the same type in the constructor. Inversion of the order parameters becomes likely. Example the constructor takes 3 strings


Bug: Object created without mandatory parameter
Some instance variables are added with setters. There is no guarantee that every user of the object thought of setting at least the mandatory ones. One single instantiation without the mandatory parameter suffice to create a bug, that takes the form of null pointer exceptions or a reference to undefined (JS) at  runtime. It can also take the expression of inconsistent behaviour if the depending code handles null as a special flag (see Null-Flag bug-generator). Alternatively it complexifies all the client code with checks to see if the parameter has been set. Remember those if (object != null) { .. } blocks?

Prevention pattern: All mandatory parameters in constructor
It is extraordinary easy to prevent this type of bug, simply by enforcing all mandatory parameters in the constructor(s). 

If there are several combinations of parameters we can use  several constructors or for languages that allows only one constructor we can use static factory methods, that enumerate the valid ways instantiating an object. e.g.

    
private constructor(mainCourse, starter?, dessert?) {...}

public static withoutDessert(mainCourse, starter) {
return new Menu(mainCourse, starter)
}

public static withoutStarter(mainCourse, dessert) {
 return new Menu(mainCourse, null, dessert)
}

Bug: Object contains invalid data
We might instantiate a phone number assuming that we always feed a string containing the country code country code. So when we try to call this number we get a failure or we call someone in another country. Likewise we might accept some IBAN number without validating the key. Later when we post it to some webservice that does validation, then we need to report an error to the user in an asynchronous way like sending an email, sms etc. Handling bad data late is always more costly than just rejecting it on input.

Prevention pattern: assertions in the constructor
Do validations in the constructor. You can mostly get away with throwing an error and only catching it at the top level, like a generic error handler, a very common pattern in the world of REST services is to map Error objects to HTTP status codes via a generic handler.

The reason we prefer doing the validations in the constructor rather than doing them before construction is because it  guarantees that the validation is made.

Bug: Constructor parameters are switched

For instance our menu from above takes strings mainCourse, starter and dessert as parameters. It is very easy to switch the order

Prevention pattern: Type parameters 
Introduce distinct types for each parameter i.e. MainCourse, Starter and Dessert. This makes it impossible. While this might seem a bit clunky in some mainstream languages it's also a step towards the removal of primitives which adresses another problem, namely the bug generator Primitive Obsession.

Prevention pattern: pass a map/dictionnary or use a parameter object or yet a builder
if each parameter has a name that is visible in the code we reduce the chance of a bug. It is harder to put something in front of the wrong name, like

    { dessert: 'pizza royale', mainCourse: 'chocolat mousse'} 

than it is to make a mistake of order. You might recognize the concept of Connascence of name vs position

Bug: Object not fully initialized before use
Let's imagine an object where we have to call an initialisation method after instantiation like the well known init(). The code gives no guarantee that this will always be done For instance forgot to call init(). The effect of this bug is not dramatic as  in most cases it'll just confuse the developer for a long time as to why the app doesn't work correctly. It rarely slips into production, just slows down the development.

Prevention pattern: call init() in the constructor
Whenever possible.

Prevention pattern: use a factory method
So that the fragile sequence is only in one place. Or refactor so that you pass the result of the init() method to the constructor. i.e the init() method becomes static and/or is moved away from the class all together. e.g.

public constructor(resultOfInit) {}

Prevention pattern: when two objects references each other
When there's a cyclic dependency between two objects, this can be eliminated on the type level by interfaces but the runtime dependency might remain. Then one must be instantiated before the other. We have at least two options for solving this. 1) It might be possible to extract a third object on which the two others depend on, thus eliminating the cyclic dependency, but more often 2) we make this more explicit, like Spring's @PostConstruct. The benefit is that it becomes easy to find all such objects.

There's no particular conclusion to make. It documents the problems and a range of alternative solutions. 

Credits to Peter Kofler whith whom we detailed the bugs and prevention patterns


mardi 1 mai 2018

Bug Generator: Use of indices

Let me just start by stating what I mean by a Bug Generator. It's a style of code that is likely to contain bugs or produce bugs in the future as the code is extended. This is of course an anti-pattern. There are corresponding Prevention Patterns, basically less error-prone alternatives. That being said, let's dive into the Bug Generator Use-of-indices.


Use of indexed access is low level, off-by-one errors are very common. Also index out of bounds can happen. Usually we can simply avoid this by using higher level constructs such as for-each-loops and higher-order functions such as map and filter.


Bug: Off-by-one errors

We access the data by some index. The problem can range from some simple error in a loop construct. For instance we use <= instead of < in loop. To harder-to-spot errors like passing the index to some function and using the index while modifying it by a -1 or +1. 
A basic example of this. Say we need to find the first cat in a list of animals. The bug will only occur when there is no cat in the collection

Bug: Index-out-of-bounds 

Variation of the above bug. This is off-by-one where we actually step outside the array.

Prevention pattern: use lambdas and higher-order-functions

higher order functions like map, filter, some/first, etc have already implemented the looping and we just have to provide a function that the higher order function will use on each element.

Prevention pattern: for-each-loop

If we really must use imperative style

Prevention pattern: link the structure length to the index calculation

E.g. modulo on length. An example would be picking cards from a deck. Lets assume that whenever we get to the end of the deck we're supposed to start from the beginning. A naïve implementation would be to

Prevention pattern: Wrap the array and index in a class (they are nearer).

This is particularly useful when the same calculation is done in several places. Whenever we have a class it is easy to find the code we need to manipulate the date inside. Another advantage is that the behaviour becomes easily testable when isolated in a class.
It'd be very easy and natural (i.e. likely) that we'd test getNextCard both by calling it many times in a row and with large values of someStep.

This solution is related to the Bug generator Primitive-Obsession that will probably be described in the future.

Credits to CodeCop (Peter Kofler) with whom I've worked a lot to explore the concept of Bug Generators. We sketched out this pattern together.