Search code examples
coding-stylecode-readabilitycode-structure

Code structure: should I use lots of functions to increase readability?


My question has Bash and PowerShell scripts in mind, but I suppose it applies to other languages as well.

It is my understanding that the purpose of a function is to perform the same (or a very similar) task multiple times. This decreases the amount of code in the script and it also makes it easier to maintain.

With that in mind, if you discover that your script only calls a function one time then there's no reason for that function to exist as a function. Instead, you should take the function's code and place it in the location where that function is being called.

Having said all that, here's my question:

If I have a complicated script, should I move each section of code into its own function even though each function will only be called once? This would greatly increase the script's readability because its logic (the functions) would all be at the top of the script and the flow of execution would be at the bottom of the script. Since 50 lines of code would be represented by just 1 line, it would be much easier to understand what the script is doing.

Do other people do this? Are there disadvantages to this approach?


Solution

  • Having functions also increases readability. So a bash script might look better and be easier to follow if it reads:

    getParams()
    
    startTask()
    
    doSomethingElse()
    
    finishTask()
    
    # implement functions below
    

    even if the function implementations are simple, it reads better.