zzz6519003 / blog

My blog about coding
4 stars 1 forks source link

Why Encapsulation? #145

Open zzz6519003 opened 4 years ago

zzz6519003 commented 4 years ago

In the 1960s and 1970s, programmers were grappling with timing dependencies and resource conflicts caused by trying to share the same memory resources between different operations running in non-deterministic sequences. They were also frustrated by the need to couple code to a specific data structure representation of the program state. In the 1970s, Alan Kay was inspired by composite data structures from Ivan Sutherland’s Sketchpad thesis, developed between 1961 and 1963 at MIT and Simula developed in the 1960s by Ole-Johan Dahl and Kristen Nygaard at the Norwegian Computing Center in Oslo. Alan Kay was involved in ARPAnet research and design, had a background in science and math, and was particularly inspired by how cells were encapsulated by a membrane and communicated via message passing. All those ideas came together to form the the foundations of OOP: encapsulation and message passing. The trouble with shared mutable state is that if your input state depends on some other instruction’s output state, and any sort of concurrency arrises, it creates race conditions. If you change the order in which instructions are called, it can alter the results. Mix in any sort of non-determinism in sequencing, and the result is chaos: unpredictable, unprovable, seemingly random application state. Sometimes it works. Sometimes it doesn’t. Encapsulation is one approach to deal with this problem. Encapsulation also solves another interesting problem. Imagine you have an aggregation of data you need to process. One way to do it is to first decide on a data structure to represent the data. If you start with the implementation details (let’s say an array), and everything that uses it is aware of its structure, and can create tight coupling with the data structure that can make it difficult to change that implementation later. What if you eventually want to swap the array out for a stream, or a tree, or some other data structure? If everything knows the implementation, it may be too late. But when we encapsulate those implementation details behind a public interface, and then everything that uses the object does so only through its public interface, it’s easier to change the implementation details later. To illustrate, imagine you have a data structure which stores numbers, and you need a way to multiply the stored values by two: