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