# Program readability and tricky logic

Readability and comprehensibility are amongst the most important attributes of a program. Readability can be defined as how easy a piece of software is to read and understand. There are a number of programmers that love to write complicated code. Sometimes it is because they are trying to be clever, and other times because they haven’t quite thought through the logic of the code they are writing. Consider the following algorithm snippet:

``````! Check code for things that go bump in the night
if (not(engineCheckfail()) and not(parkBreakOn()) and not(wheelChocks())) then
! algorithm to taxi plane
end``````

A more readable piece of code would involve changing both the comment, and the logic of the conditional, even if it means changing the subprograms that return values.

``````! Check conditions for plane to taxi - if the engineCheck is okay and
! the park break is off, and wheel chocks have been removed, the plane can taxi

if (engineCheck() and parkBreakOff() and wheelChocksRemoved()) then
! algorithm to taxi plane
end``````

Here is another example of a piece of Fortran code (adapted from The Elements of Programming Style, Kernighan and Plauger):

``````do i = 1, n
do j = 1, n
V(i,j) = (i/j) * (j/i)
end do
end do``````

This tricky piece of code creates an identify matrix. In Fortran integer division truncates to zero, so when I<j, i/j is zero, and when j<i, j/i is zero. When both i and j are equal, (i/j) * (j/i) = 1. Basically this code adds 1’s on the diagonal. It’s a neat piece of code, but there are easier ways of doing this, without having to add a comment to explain what is going on, and without having to use two integer divisions and a multiplication. Below is a more readable version of the code.

``````do i = 1, n
do j = 1, n
if (i == j) then
V(i,j) = 1
else
V(i,j) = 0
end if
end do
end do``````

But this can be improved even further, without loosing anything in the way of readability.

``````V = 0
do i = 1, n
V(i,i) = 1
end do``````

Bottom line? Don’t write clever code that isn’t readable, or isn’t properly documented.

## One thought on “Program readability and tricky logic”

1. tungvu3196 says: wow, new post almost every day, so great!

This site uses Akismet to reduce spam. Learn how your comment data is processed.