When we write code, we try to think ahead to what possible changes we may need to implement in the future. There are many ways that we can implement these changes, ranging from slapping together a quick patch, methodically going through the code and changing all the affected parts, or writing the code in such a way that anticipated changes can be added in with just one or two small adjustments. This last method is what “encapsulate what varies” means. Writing code will often cause us to think about what future changes we need, and by isolating those parts of the code we can save ourselves time in the future. I found an article that does a good job explaining this concept, and while reading through it I was reminded of a recent project where using encapsulation ended up saving me a lot of time and headaches in the future.
The specific event that the article caused me to remember occurred during my most recent internship. One of the projects I worked on was a script that would automatically assemble 3D CAD models of of any of the systems the company was working on at the time. This script needed to read the system specifications from a database and then organize that data, identify key parts of the system, and figure out how it is assembled so that it can then send those instructions to the CAD software and create the 3D model. It was a big project, and I and the other intern working on it were daunted by the amount of ever changing data that would need to be accounted for. Many systems were of a unique design, and as such we couldnt use the same exact code for all systems. The engineers we were attatched to for this internship introduced us to something called python dataclasses. These essentially allowed us to structure parts of our code that we knew were going to be subject to change in such a way that adding or removing certain data points from the database doesn’t break the overall program. If any changes arise, we only need to alter the related dataclasses for the rest of the code to be able to work with the new change. Without these we would have had to create new methods/classes for each unique change every time it came up; which is not something anyone wanted. I am glad I found out a way of “encapsulating what varies” since I can now write better and more future-proof code by isolating the parts that I believe will be changed the most often.
https://alexkondov.com/encapsulate-what-varies/
From the blog CS@Worcester – Sebastian's CS Blog by sserafin1 and used with permission of the author. All other rights reserved by the author.