Code, aesthetics and symmetry
It might sound funny to mention aesthetic qualities like symmetry when speaking about source code. It is exactly the principle that Kent Beck mentions in his book Implementation Patterns. It has to do with inner workings of our brain. These qualities are the way to communicate with fellow programmer on another level. I’d say symmetry might be put under more general “Consistency” principle that Abrams and Cwalina are so keen about. And it is definetly in the spirit of Principle of least surprise.
What got me thinking about it is a bug I investigated recently that had to do with two base java classes: java.net.URL and java.net.URLConnection. The symptom was a generation of leaking file handles, resulting in server hanging after few hours of operation.
Take a look at this java code:
URL url = configuration.getURL();
URLConnection connection = url.openConnection();
long date = connection.getLastModified();
Now, I’d typically put method open on the connection object. If you take a look at URLConnection, you will see that the class does not have the close method. That’s all right, following the symmetry principle, it would be then consistent to place closeConnection method inside the URL class. Alas, neither the URL has the method that closes the connection!
This was the source of our bug. The programmer had to open the connection in order to read getLastModified. But, since neither URL nor URLConnection had the close method, he “forgot” to close the connection. The solution is to do the following after reading the date:
InputStream stream = connection.getInputStream();
stream.close();
No wonder the programmer forgot to close the connection; there was no obvious method he could call to do so. I haven’t bothered to take a look at the code of these classes, but it seems unlikely that there was no other option when designing them. Had the authors thought about symmetry when creating URL and URLConnection classes, a nasty bug could have been averted.
Posted in Programming, Refactoring






