开发者

What is Encapsulation and how can it defend abstractions against corruption?

It's quoted from a report by Bjarne:

Encapsulation – the ability to provide guarantees that an abstraction is used only according to it开发者_StackOverflows specification – is crucial to defend abstractions against corruption.

Can someone explain this?

Thanks


Let's say you have a class with public methods that you must use to perform some action. The specification of the class say that, in order to do this action, you must configure the class in a specific way (call this method, set this property, etc).

The problem with situations like this is that it might not be clear what needs to happen or in what order. So the API for the class is hard to use and confusing for the majority of developers.

With encapsulation, you can "encapsulate" not just the class but the algorithms to use it within a second class. This second class sets up the original one, configures it, and manages its lifetime. It allows you to access the API without needing to know how to use it correctly, as the encapsulating class takes care of that. This is sometimes called the Facade pattern.

Your quote also says "is crucial to defend abstractions against corruption." What this means is that when you abstract some process into a class, different implementations of that process should not require the abstraction to be handled differently.

For example, you might have two implementations of a report writer class. You should be able to treat each of them exactly the same without ever knowing how they are implemented (the meaning of abstraction). However, if one cannot be run in a multithreaded apartment state (MTA), you have to "know", before you use it, that it is time to transition to an STA thread. This magical "knowing" is required by the implementation of the class. This is a "leaky abstraction."

With encapsulation, you could prevent this "leak" by, within the encapsulating class, making the transition to an STA thread within the encapsulation, preventing the abstraction from leaking details of its implementation.


It means that the object grant premission only to certain things it needs to expose, and deny you from using data it doen't want you to use.

The most classic example is properties: Yout fields will be private (or protected). If you would like to expose them for read or write, you'll add a getter\setter, accordingly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜