我觉得“organize objects with class”这个命题特别好。它说明白了class是一种组织工具或者组织方式而已,而不是核心的东西——核心的、基础的东西是object。
David A. Black先生说过:Defining a class lets you group behaviors (methods) into convenient bundles, so that you can quickly create many objects that behave essentially the same way. 这就说明class存在的意义是:按照某种目的把behaviors打包。
比方说:地上胡乱堆放了一堆铁钉、螺丝、图钉、胶带、创可贴、胶水。妈妈叫你把这些东西分类归置好。你会怎么分类?我会把铁钉、螺丝、图钉挑出来放一个盒子里,贴上一个标签“铁钻物”;把胶带、创可贴、胶水放到另一个盒子里,标作“粘合品”。这就是“分类”——在英语里面叫class。为啥要这样分啊?因为铁钉、螺丝、图钉有类似的行为——在英语里叫behavior,在程序里我们通常叫method。
Classes are object factories. Classes are also special objects: They’re the only kind of object that has the power to spawn new objects (instances). Nonetheless, they are objects.
Thursday, March 15, 2007
Organizing objects with class
Labels:
Class Method,
Convention Mine,
Instance Method,
Philosophy
Sunday, March 11, 2007
Structured Freedom provided by Rails
You’re in charge of naming and writing the methods, but Rails provides an infrastructure that rationalizes and pre-systematizes the code for you.
An example of “structured freedom” are the method hooks available to you in your model definition files. A method hook is a method that you may, but aren’t obliged to, write; and if you do write it, it’s automatically called at a predefined point during program execution.
For example, if you write a method called before_create in one of your model files, then that method will be called automatically every time a database record corresponding to an instance of that model is created. This allows you to gatekeep the data in an orderly fashion and to manage your database at a low level while still writing everything in Ruby.