Tag Archives: Scala

Surfacing Hidden Design: Seeking A Better Alternative To Interrelated Mutable Fields

What is better, a bunch of mutable boolean fields and methods operating on them, or an explicit expression of the individual states and transitions between them? Lets study an example from a simulation of the progression of a multi-stage infection.

1. Design hidden in primitive mutable fields and methods

The following class, with a number of interrelated mutable (public) fields, which I should have completed with methods for transitions between their states, made me really uneasy (a var is a mutable field, val is immutable):


class Person (val id: Int) {
var infected = false
var sick = false
var immune = false
var dead = false
// to complete with simulation logic
// [infection progression]
}

The fields keep the state of the progress of an infection. They depend on each other – f.ex. when sick, the person must also be infected, while when dead, she must not be immune.

The progression of the infection is: healthy -> infected and infectious with the chance of 40% (but not visibly sick yet) -> on day 6 visibly sick -> on day 14 dies with the chance of 25% -> if not dead, becomes immune on day 16 – not visibly sick but still infectious -> healthy on day 18.

The problem I have with keeping the state in a bunch of fields is that there is no explicit expression of these rules and that it opens for defects such as setting sick to true while forgetting to set also infected. It is also hard to understand. You could learn the rules by studying the methods that alter the fields but it requires a lot of effort, it isn’t easy to distinguish between an incidental implementation detail and intentional design and this code does not prevent mistakes like the one described.

Continue reading