Skip to Main Content
Prefactoring
book

Prefactoring

by Ken Pugh
September 2005
Intermediate to advanced content levelIntermediate to advanced
240 pages
6h 28m
English
O'Reilly Media, Inc.
Content preview from Prefactoring

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Understanding Unittest.Mock

Understanding Unittest.Mock

Mario Corchero
Java™ Performance

Java™ Performance

Charlie Hunt, Binu John

Publisher Resources

ISBN: 0596008740Supplemental ContentCatalog PageErrata