Principle of Least Astonishment Explained

designdesign-patternsobject-oriented

In programming what is called Principle of Least Astonishment? How is this concept related to designing good APIs? Is this something applicable to only object oriented programming or does it permeate other programming techniques as well? Is this related to the principle of "doing a single thing in your method and do it well" ?

Best Answer

The Principle of Least Astonishment is applicable to a wide range of design activities - and not just in computing (though that is often where the most astonishing things happen).

Consider an elevator with a button next to it that says "call". When you press the button, the payphone rings (rather than calling the elevator to that floor). This would be considered astonishing. The correct design would be to put the call button next to the phone rather than the elevator.

Next, think of a web page that has a pop up window that shows a windows style error with an 'ok' button on it. People click the 'ok' button thinking it is for the operating system and instead go to another web page. This astonishes the user.

When it comes to an API...

  • Think about a toString() method that instead of printing out the fields returns back "to be implemented".
  • An equals() method that works on hidden information.
  • Sometimes people try to implement a sorted list class by changing the add method to call sort() on the array afterwards - which is astonishing because the add method is supposed to append to the list - this is especially astonishing when one gets back a List object with no knowledge that somewhere deep inside, someone violated the interface contract.

Having a method that does one distinct thing contributes to reduction of astonishment, however these are separate principles in API design. The four principles often touted as "good API design" are (from this pdf - just one instance of such a presentation. The links at the end of this particular one make for good reading):

It is potentially astonishing for someone to have a class that tries to do everything - or needing two classes to do a single thing. It is likewise potentially astonishing for someone to mess with the internals in odd ways under the covers (I find open classes in Ruby to be a source of never-ending astonishment). It is also likewise astonishing to find two methods that do apparently the same thing.

As such, the principle of least astonishment underlies the other API designs - but it, itself, is not sufficient to simply say "don't have an astonishing API."

Further reading (from the UI perspective) - an IBM developer blog titled The cranky user: The Principle of Least Astonishment