lua-users home
lua-l archive

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


On Wed, Jul 27, 2011 at 07:37, Axel Kittenberger <axkibe@gmail.com> wrote:
>> "...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
>
>

Lua's first-class functions are another good way to reduce indentation, e.g.:
local function func(str) return '[' .. str:upper() .. ']' end
doThingsWith(foo:gsub('%d+', func), bar:gsub('%a+', func))

Especially if you're like me and always wrap lines at 80 characters,
this is a lot cleaner than providing the function inline in the gsub
call (and duplicating it, no less!).

-- 
Sent from my toaster.