Reflections on bugs
• Mark Eschbach
I remember hearing a hype over the last few years how Swift is going to save us all from the perils of nil
dereferencing. Fast forward to now, where I’m responsible as a member of a team to support a product which is primarily comprised of Swift and I’ve got to say most of our bugs stem from the assumption a vaule is not nil. There are two classes of problems I’ve found so far: the whole InterfaceBuilder ecosystem (design + runtime + etc) doesn’t allow graceful initialization so we have UIVeiwController
s in a valid state; and we can’t correctly describe the life cycle of a variable through state transitions of the enclosing object.
For the InterfaceBuilder class of problems we’ve done a few things to mitigate. We’ve began using the Type!
statement for the actual UIView
family of components. We are generally aware enough of the lifecycle of these components as outlets and the crashes occur primarily during development time. Actually I’ve never encountered a production crash from this approach. To resolve required object graphs being attached we’ve haven’t found a perfect method yet. Previously we had very WET code instantiating the target UIViewController
and setting the required state. Unsurprisingly this lead to inconsistent state and crashes. Recently we’ve began centeralizing the instantiation and configuration into the project’s primary UIViewController
as a series of exentsions. This allow optioality enforcement but time will tell if how this sorts out.
As for the lifecycle approach we haven’t tackled to much there yet. I suppose we could use Swift enumeraitons which would force the concerns to compile time and describe when the variable is present or even not optional. Primary problem with this approach would be the switch
statements or conditionals which would quickly lite the code. The enumeration approach also doesn’t aliviate us from dealing with invalid state when they do occur. For now I’ve settled on loudly logging the error, trying to catch it earlier with each bug report which comes in. After a short period of time this has already allowed us to source the root cause of several hard to find bugs. I’m hoping this will be more fruitful in the future.
My goal is to drive out as many bugs we can find the source of. I’m not so sure about using enumerations however these other techniques appear to be providing a reasonable return on investment. It will be exciting to see where they go in the future.