12

Possible Duplicate:
How would you know if you've written readable and easily maintainable code?

It is often said that readability is perhaps the most important quality-defining measure of a given piece of code for reasons concerning maintainability, ease of understanding and use.

What defines the word readable in context of program source code? What kind of definitive aspects are there to code readability?

I would be grateful with code examples of readable code, along with reasoning why it is readable.

1
  • Step 1: Read the code. Step 2: Did you understand the code? Easily? Did other people you work with have the same experience? If yes, yes, and yes, congratulations! You have readable code.
    – Caleb
    Aug 30, 2012 at 6:57

3 Answers 3

13

Readability, to me, means that the code is easy to follow, logically.

  1. Standards of indentation and formatting are followed, so that the code and its structure are clearly visible.
  2. Variables are named meaningfully, so that they communicate intent.
  3. Comments, which are present only where needed, are concise and adhere to standard formats.
  4. Guard clauses are used instead of nested if statements.
  5. Facilities of the language are used skillfully, leveraging iteration and recursion rather than copy and paste coding.
  6. Functions are short and to the point, and do one thing.
  7. Indirection is minimized as much as possible, while still maintaining flexibility.

Unreadable:

        try:
          if item[1][2]=='1':
            qtytype='0'
            qty=str(item[1][0])
            items=item[1][0]
            amt='0.0'
            tot_amt=str(float(item[1][1])/100)
#              tot_amt=str(float(int(item[1][0])*int(item[1][1]))/100)
          else:
            qtytype='1'
            items=item[1][0]
            amt='0.0'
            tot_amt=str(float(item[1][1])/100)
            qty=0
            for entry in item[1][4]:
              qty+=entry[0]
        except TypeError:
          eType, eValue, eTraceback = sys.exc_info()
          print >> sys.stderr, time.strftime("%Y-%m-%d %H:%M:%S"), str(traceback.format_exception(eType,eValue,eTraceback))

Readable:

item_approved = (item['approved'] == '1' and item['active'] == '1')

if item_approved:
    try:
        db_item = item.get_db_record(item['id'])
    except DoesNotExist:
        db_item = item.create_db_record(**item)

    item.approve(db_item)
    db_item.save()

    publish_event(item.events.APPROVAL)
5

Section 9 (pg 39) of http://c0x.coding-guidelines.com/Introduction.pdf gives some background for the C language coding guidelines. It is a referenced work with sociology & psychology studies. It's addressing more the question 'why code should be readable' but does address readability itself. I found it quite interesting, albeit a little 'academic' in places.

2

Similar questions have been answered before. See https://stackoverflow.com/questions/550861/improving-code-readability for example.

Readable code is code that clearly communicates its intention to the reader. Code that is not readable takes longer to understand and increases the likelihood of defects.

Some things that increase readability:

  1. Use whitespace to separate disparate areas of code. For example, indent code blocks like "if" statements. Leave blank lines between methods/functions or related lines of code within a method/function. This allows the brain to segregate the code even before the characters are read.
  2. Use meaningful variable and method/function/class names. Follow the standard practice for the language and use terms from the problem domain if possible. The meaning and use of something should be evident from its name. Names should also be consistent (GetX(), GetY() and GetZ() rather than get_X(), LoadYFromDatabase() and getVar(Fields.Z));
  3. Comment effectively. Avoid obvious comments ("The GetX() method returns the current value of x"). Comments should say what the code intends to do, how it relates to other parts of the code and any assumptions ("Argument "a" cannot be null. The code throws an exception if a is null").
  4. Following established design patterns for the language, library or problem space. For example, avoid repeating code (called DRY or Don't Repeat Yourself). This wastes time as the reader tries to look for differences or find the correct piece of code to fix.
  5. Keep it Simple (KISS principle). For example, avoid premature or unnecessary optimization. Optimization has its place but code can often be optimized without impacting readability.

Arguably the single most important aspect is consistency. It is easier to understand code if the reader knows what to expect and where to look. If the project uses conflicting variable naming and commenting styles, for example, the reader has to waste mental effort learning new styles and context switching.

The code's author may be a poor judge of readability since they may be invested in the code or be too deep in the problem to take a step back and look at it through others' eyes. Code reviews help here.

Remember that not all code is going to be readable all the time. Developers often have to write code in a hurry when they are tired using unfamiliar libraries. Poor readability should be treated like technical debt and refactored.

Not the answer you're looking for? Browse other questions tagged or ask your own question.