Code Is Hard to Read
Revision as of 08:51, 19 July 2009
Each programmer has an idea in their head regarding "hard to read" and "easy to read". This depends on many factors:
- Implementation language. Some syntax is easier to read than others, XSLT anyone?
- Code layout and formatting. Pet hates like "where do I place the curly bracket" and indentation.
- Naming conventions. Try 'x' over 'userStatus' over '_userstatus'.
- Viewer. Even the IDE or tool used will contribute to readability.
The short note is that Code is hard to read! The amount of math and abstract thinking required to read through the most elegant of programs is taken for granted by many programmers. This is why there are reams of good advice and tools available to help us produce readable code. The points above should be very easy for any professional programmer to address, but the fifth point I left out is:
- Solution design. The most common problem - "I see what's happening here but it could be done better".
This addresses the "art" factor in programming. The mind thinks a certain way and some solutions will just sit better than others. Not because of any technical or optimisation reason, it will just "read better". As a programmer you should strive to produce a solution that addresses all of these 5 points.
A good piece of advice is to have someone else glance at your solution or come back to it a day later and see if you "get it" first time. This is common advice but very powerful. If you find yourself thinking "what does that method/variable do again" - refactor! Another good litmus test is to have a developer working in a different language read your code. It's a great test of quality to read some code implemented in a different language to what you are currently working on and see if you "get it" straight away. Most scripting languages excel at this. If you are working on Java you can glance at well-written Ruby/bash/DSL and pick it up immediately.
As a rule of thumb, programmers must consider these five factors when coding. Implementation language and Solution design are the most challenging. You have to find the correct language for the job - no one language is the golden hammer. Sometimes creating your own Domain Specific Language (DSL) can vastly improve a solution. There are many factors for Solution design, but many good concepts and principles have been around for many years in Computer Science, regardless of language. Uncle Bob's Clean Code is a great place to start.
All code is hard to read, you must be professional and take the time to ensure your solution has flow and reads as well as you can make it. So do the research (metrics!) to back up your assumptions, unit test by method and question dependencies - a simple, readable implementation is head and shoulders above a clever-but-confusing, "look at me" implementation.