lua-users home
lua-l archive

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



> On Jun 26, 2019, at 9:44 PM, Abhijit Nandy <abhijit.nandy@gmail.com> wrote:
> 
> Hi,
> 
> My Lua functions often exceed 500 lines and I then need to refactor blocks in if statements and loops to a separate function. I use MSVC a bit and it has a plugin called Visual Assist which can convert a given chunk of C/C++ code into a function with the proper required arguments. Its very useful in a hurry :)
> 
> Has anyone tried something similar for Lua? Basically I would want to give it a block of code and it would need to deduce the required arguments for the function and give me back the code string as "function (args...) ... end".
> 
> I am going to try it today with regexes and maybe ltokenp, but wanted to check if someone has already tried it.
> 
> A simple converter could perhaps detect patterns like "<0 or more spaces><1 or more valid variable name chars><Lua delimiter like '(' or ',' >" and then put the variable names into the argument list if they are not present in _G. Reserved words skipped.
> 
> Not sure of the relevant part in lexer.c yet, that I could perhaps convert to do this.
> 
> Thanks,
> Abhi

I’m always worried when people say “my function is X lines long and I need to refactor it…”. Yes, many times a long function MAY be better when broken up, but the “function police” who claim such a thing is ALWAYS true are talking nonsense imho. Some functions are complex and inherently must be long.

To my mind, refactoring is about CLARITY, and breaking up large functions is only one way to do this (and not the best, either, since in languages that lack lexical nesting it may expose internal helper functions to abuse). Other ways to clarify long functions are to carefully control function-wide state vs local “working” state, and re-factor deeply nested loops into single-layer loops with state machines.

Knowing when to break up a function falls into the “art” side of good software development; doing so automatically based on line count has always seemed dubious at best to me.

—Tim