The Rules of Class-Based OOP.
作为一门研究 programming languages 的课程,OOP 是一个避不开的话题。这一节通过介绍 Ruby —— a dynamically typed OOP language,来引出 functional v.s. OOP 这一历史悠久的命题。
Taken together, ML, Racket, and Ruby cover three of the four combinations of functional v.s. object-oriented and statically v.s. dynamically typed.
Part C 的内容非常多,因此也分为两节笔记;但这里将不会详细记录 Ruby 的 semantics。若想参考这部分的内容,详阅我在博客园上的笔记或课程提供的总结材料 section8sum.pdf。
Object-oriented programming, which we abbreviate OOP, is as follows:
- All values (as usual, the result of evaluating expressions) are references to objects.
- Given an object, code “communicate with it” by calling its methods. A synonym for calling a method is sending a message.
- Each object has its own private state. Only an object’s methods can directly access or update it.
- Every object is an instance of a class.
- An object’s class determines the object’s behavior.
这些规则在绝大多数 OOP 语言中成立,但仍有例外:例如在 Java 或 C# 中,某些值 (numbers) 并不被视为对象,这违反了规则 1;并且存在一些方法使得对象的私有域被公有访问,这违反了规则 3。
比起这些语言,Ruby 将以上的规则贯彻的更加彻底,因此有时其也被称为 pure OOP language.