What is the Definition of Elegant Code?
I always try to write elegant code, but what does that mean exactly? Up until now, it was always a "I knows it when I sees it" kind of thing, but I believe I have captured the key points that define elegant code for myself.
In commenting an algorithm I wrote recently in theHeron interpreterfor resolving types,I felt an apology was in order to the reader. The algorithm I used for resolving types didn't feel very elegant, but I couldn't think of anything better. The problem I had at first was that I wasn't sure what made the algorithm inelegant.
In short the algorithm is this: when creating the abstract syntax tree (AST) I create place-holders of type "UnresolvedType" which contain the type name as a string. These are then replaced with the concrete type during a second pass over the AST. This is because the necessary information to create a proper HeronType is not available until the AST is fully constructed.
In forcing myself to try and write the comment, I realize that the source of inelegance was that it was too easy for a programmer to forget to resolve a type afterwards (which I had in fact done, and am currently correcting!).
However, I also realized that some of the other criteria I have for elegance were satisfied. This prompted me to summarize herewhat my criteria for elegant code:
- It is succinct
- It is easy to understand
- Each function does one well-defined task
- It conveys the programmer's intent
- It reflects the problem domain
- It is easy to modify and reuse
- If it fails, it is easy to identify that it is has failed, where it has failed, and why it has failed.
- Its behavior (in good and bad conditions) is easy to predict
So what is your definition of elegant code?

