Original Blog: https://blog.ploeh.dk/2024/06/12/simpler-encapsulation-with-immutability/
For this post, I’ve decided to write about encapsulation, and how implementing immutability in a program can make implementing encapsulation scalable and overall easier. I chose this topic because it seems like an interesting look at how concepts learned in a course I’m currently taking would appear in projects designed for a large user base.
Encapsulation is a widely used concept of object oriented programming, and for good reason. It allows developers to make efficient methods and functions with only the necessary amount of information, and also makes the scope of variables clear and defined, leading to debugging and problem identification becoming much easier than they would be without the use of encapsulation. A problem with encapsulation, however, is introduced in the blog “Simpler encapsulation with immutability”, by Mark Seemann. Seemann identifies a common difficulty encountered when implementing encapsulation on a large scale: How do we ensure that invariants are included? Invariants are defined as conditions within the program that remain true regardless of changes made to other areas of the code. This can include class representation, loop invariants, or other assumptions about the logic of your program. When implementing encapsulation at a large scale, it can be difficult to preserve this property in as many areas of the code as possible, with function variables taking different states throughout many points in the program.
A solution the author offers is to simply make the object immutable, guaranteeing that through whatever change it may see when the program is executed, it’s value can’t change. The author uses the example of making a program which models a priority list to model to difference in difficulty in preserving invariants, with the invariant being that the sum of the numbers in that list must be 0. Without defining each of the members of the list as immutable, it’s difficult to manually maintain at all times, while if the objects are immutable, you can guarantee that at no point will they not sum to 100.
In summary, the author outlines common problems developers have with implementing encapsulation while preserving invariants at large scales. He then provides the solution of immutability to ensure that at all times, objects desired to be invariants will be unchanging. Some thoughts I have about the blog are if making an object immutable could present some unwanted limit to the developer, and if that were to be the case, is there another solution which preserves invariants at a large scale without ensuring that a condition about an object only sometimes changes.
From the blog CS@Worcester – My first blog by Michael and used with permission of the author. All other rights reserved by the author.
