Friday, November 27, 2020


 Encapsulation and explicit state are most useful when used together. Adding state to declarative programming makes reasoning about the program much harder, because the program's behavior depends on its state. For example, a procedure can do a side effect, i.e., it modifies state that is visible to the rest of the program. 

Side effects make reasoning about the program extremely difficult. Bringing in encapsulation does much to make reasoning tractable again. This is because stateful systems can be designed so that a well defined property, called an invariant, is always true when viewed from the outside. This makes reasoning about the system independent of reasoning about its environment. This partly gives us back one of the properties that makes declarative programming attractive.

An invariant says that the component is not behaving incorrectly; it does not guarantee that the component is making progress toward some goal. For that, a second property is needed to mark the progress. This means that even with invariants, programming with state is not quite as simple as declarative programming. A good rule of thumb for complex systems is to keep as many components as possible declarative. State should not be smeared out over many components. It should be concentrated in just a few carefully selected components.