面向对象设计技巧[Object Oriented Design Tips] - 2

Pick nouns or noun phrases as classes

Identifying objects is easy, they should always be nouns. As we have seen in the Circuit Controller example, we picked up nouns from the requirements as classes in our design. Even when you invent classes, keep in mind that they should be nouns. Abstract concepts don't qualify as object names. 

Naming the objects is extremely important in object oriented design. Chances are that if you name your object correctly, the designers and maintainers will assign it functionality that fits its name. Also note that, if you have trouble naming an object, you probably have the wrong object. At this point go back and look at the problem again and see if you can pick an alternative object.

选择名词或者名词短语作为类的名称

识别对象是简单的,因为它们一般都可以用名词来描述。就像我们在电路控制器这个例子中看到的那样,我们在设计的时候从需求中选择名词作为类名。甚至在你创造自己的类的时候,也要时刻注意类名应该是名词。抽象的概念不要作为对象的名称。

在面向对象的设计中为对象命名显得特别重要。在变化出现的时候,如果你恰当的命名了你的对象,设计和维护人员会根据它的名称指派正确的功能。同样需要注意的是,如果你发现你在命名一个对象的时候出现了问题,你可能创造了一个错误的对象。在这个时候,应该再一次回到问题本身,寻找是否存在一个可以替代的对象。
----------------------------------------------

Method names should contain verbs

In any language, actions performed by nouns are specified using verbs. Why should object oriented programming be any different? Thus make sure all the operation methods should contain verbs.

Thus the Circuit class we discussed earlier would have methods like:

  • Activate
  • Deactivate
  • Block
  • Unblock
  • ChangeStatus

Notice that the methods do not include Circuit in the name (ActivateCircuit, BlockCircuit etc.) as being methods of Circuit its clear that they refer to operations on Circuit.

方法名称应该包含动词

在任何一种语言中,用名词表现行为即为动词。在OOP中也不例外,应该确保所有方法包含动词。因此,在我们之前起到的那个Circuit 类中的方法应该像下面这样:

  • Activate
  • Deactivate
  • Block
  • Unblock
  • ChangeStatus

    要注意这些方法名都没有包含Circuit 在其中(如ActivateCircuit, BlockCircuit 等),因为在Circuit 中的方法这个事实本身就说明了这些方法是对Circuit的操作。
  • 你可能感兴趣的:(object)