没有 OOP 是否可以封装?

Is encapsulation possible without OOP?

我在面试中被问到一个问题:如果没有 OOP 是否可以进行封装,例如用程序语言?

Bob Martin 表示,如果没有 OOP,封装不仅可能,而且在 OOP 出现之前 更好

这是他 2014 年在耶鲁大学管理学院发表的 talk 的摘录。

We had perfect encapsulation. In C, all you had to do was forward declare your functions and your data structures. You didn't have to implement them. You would forward declare them in a header file, and then you would implement them in a C file. Your users would #include your header file. They could see nothing of your implementation. Perfect encapaulation. There was no way any of your users could see any of your data values. All they could see was your function signatures. They could see the names of your data structures but none of the members inside your data structures. Absolutely perfect encapsulation.