6.2. Three Laws of Objects

Isaac Asimov proposed three laws for robots in his book, I, Robot.[*] Objects are a lot like robots. They are asked to perform certain operations with an expectation that those operations will be performed correctly. In addition to the maxims stated in the preceding section, you might consider the Three Laws of Objects. These laws can be applicable for a program as a whole, as well as for an individual object:

[*] They are: 1. A robot may not injure a human being, or, through inaction, allow a human being to come to harm; 2. A robot must obey orders given it by human beings, except where such orders would conflict with the First Law; and 3. A robot must protect its own existence as long as such protection does not conflict with the First or Second Law.

  • An object shall do what its methods say it does

  • An object shall do no harm

  • An object shall notify its user if it is unable to perform a requested operation

Let us look at these laws in a little more detail:

An object shall do what its methods say it does

This law covers two concepts. The first is that a given method has a name that specifies what it does. This concept is covered in the guideline, "A Rose by Any Other Name Is Not a Rose." The second is that the method does what can be reasonably expected by that name. (This concept is also known as the "Principle of Least Surprises").

For example, what is the expectation for a method named "remove" versus one named "delete?" This dichotomy occurs in user ...

Get Prefactoring now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.