lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> "...The answer to that is that if you need
> more than 3 levels of indentation, you're screwed anyway, and should fix
> your program."

I'm sticking to that. 4 levels of indentation get a pass, if I cant
easily help it.

Apart from restructuring everything in a cleaner way, which you need
to do anyway once in a while, there are few tricks to keep indentation
short - and IMHO the whole program more readable.

For example what I observed a lot in code from newcomers to programming:

function FUNC()
   if condition then
       ...code...code...code...code...code...
       ...code...code...code...code...code...
       ...code...code...code...code...code...
       ...code...code...code...code...code...
   end
end

So trick 1 early returns

function FUNC()
  if not condition then return end
  ...code...code...code...code...code...
  ...code...code...code...code...code...
  ...code...code...code...code...code...
  ...code...code...code...code...code...
end

Same with if-then-else statements when one part is simple and the
other complex. It gets

if condition then
  ..simple...
   return
end
...complex...

The  complex part has a level of indentation less.

In other languages "continue" can also save levels of indentation in loops.

while condition do
   ...code...
   if condition2 then
      ...code...code...code...code...code...
      ...code...code...code...code...code...
   end
end

is uglier regarding indentation than
while condition do
  .. code ..
  if not condition2 then continue end
  ...code...code...code...code...code...
  ...code...code...code...code...code...
end