The “Principle of Least Astonishment” (a.k.a the principle of least surprise (POLS)) is a guiding design principal for UIs, APIs, and interfaces of all types. Peter Seebach says:
Throughout the history of engineering, one usability principle seems to me to have risen high above all others. It's called the Principle of Least Astonishment -- the assertion that the most usable system is the one that least often leaves users astonished.
POLS plays a role in framework design, too. One framework behavior that I’ve always felt violated POLS was the ToString implementation of the System.Xml.XmlDocument class.
XmlDocument document = CreateSomeXml(); string result = document.ToString();
You’d think that calling ToString on an XmlDocument instance would give you a hunk of XML. But - it doesn’t matter how many nodes you have in the document, the ToString method will happily produce the following string every single time:
System.Xml.XmlDocument
This string represents the fully qualified type name of the object. Thanks, .NET framework! I wasn’t sure I was working with an XmlDocument. Now tell me, how do I get the XML out of this thing?
The new XML API in .NET revolves around XElement and friends in the System.Xml.Linq namespace. This API fixes the astonishment factor of the ToString method.
XDocument document = CreateSomeXml(); string result = document.ToString();
That above code yields real XML – angle brackets and all. In fact, LINQ to XML tends to “do the right thing” in many scenarios. For example, extracting an integer out of an attribute is just one cast operator away:
XDocument document = CreateSomeXml(); int i = (int)document.Root.Attribute("bar");
Now that we have all the surprises out of the way, we can all get back to work and make the world better.
Wait? What’s that?
Of course there are a plethora of options you might want to specify when producing a textual representation of an XDocument. There are encoding options, indentation options, new line options – the list goes on and on. You can get to these options with the WriteTo method of an XDocument, but not with ToString. ToString has to pick some defaults. One of the defaults in the ToString implementation is to omit any XML declaration, and this causes some people grief.
Just recently I came across a post in a Ruby form. The topic was a debate over the naming of mathematical functions, and Matz says:
Ah, please stop mentioning POLS whenever your personal expectation is
not satisfied. I'm sick of them.
Trying to follow the principle of least surprise is one thing, but never surprising anyone is impossible.
What has surprised you recently?