Encapsulating Understanding In Code
By Adrian Sutton
In most software projects, there are a few areas that are just really complex to get your head around. It’s not something that refactoring can solve, the underlying concepts are just difficult to work out. Fortunately as software developers, we can learn that information once and encapsulate it in code that will understand it for us and even apply it in new situations that we didn’t originally consider.
Recently, we’ve developed a really neat, simple example of this – the PushAndPopCalulator. A surprisingly simple class that determines the appropriate values for popDepth and pushDepth when inserting in Swing text components. The push and pop depth is a way to manipulate the element hierarchy of styled documents to precisely determine where the inserted content works out. Once you understand the details, it’s a reasonably simple concept but working out exactly what values you need for a particular insert requires a break in focus on the actual problem to divert into working out details of using the underlying APIs. It takes a little more time to generalize that to cover all the possible situations you might need.
Fortunately, we can write a single class that given a few simple parameters will handle every situation you ever need and give the right values every time. Even better, it comes with a suite of tests so that even as the code is modified and updated over time you can have complete confidence that it will still give the right answers. It’s far less likely that a bad change will be made in those tests because they’re small and focussed instead of just being an unimportant looking part of a bigger test. It’s far less likely that the code will be changed because it is isolated from the rest of the system – it stands almost entirely alone just doing what it does best day in and day out.
In the last few months we’ve applied this principle, sometimes unknowingly, with a huge amount of success. The number of opportunities we’ve opened up for improving our product is pretty exciting, and it’s made possible to see because we can now think at a higher level than before. We’ve got little digital assistants running around the product taking care of the details and we’re becoming more like the grand conductor waving in broad strokes and creating beautiful music with every movement. Then of course we wander into an older part of the code base and get ambushed – just as a reminder of why we should continue to focus on improving quality at every opportunity and encapsulating what we know today so that we can learn more easily tomorrow.