[ale] Why define one function inside another (bash, awk)?
DJ-Pfulio
DJPfulio at jdpfu.com
Wed May 24 15:58:01 EDT 2017
I learned by watching expert programmers.
One thing they all had in common is keeping any function less than 1
page in length. When I asked about it, they each explained almost the
same reason.
This was mostly because they could see the entire function on 1 screen
and understand what the inputs, outputs, and purpose for the function
was. It made unit testing easier. It made finding and logging errors
easier. It made checking for out-of-bounds inputs easier to make the
program/function/method defensive for any bad inputs. There were
exceptions for length, usually for very simple code, without any
decisions, but those didn't happen very often.
For my programming, I switch from bash/ksh/sh to perl whenever a script
is longer than 1 page. That's a rule of thumb, but it has worked well
for 20-ish years. Any bash script that it too long probably is doing
more complex things. Those are a trap for me, whereas in perl I can do
pretty much anything.
I use bash functions all the time to simplify logic.
In fact, my initial code is usually a page of comments describing what
needs to happen, in order. Then each of those comments usually becomes a
function. If a function gets too long, more comments are written and
more sub-functions are made, about 5-20 lines at a time.
On 05/24/2017 12:10 PM, leam hall wrote:
> So a usage issue? No significant performance degradation if the calling
> script is already sourcing other files?
>
> I'm looking at multiple scripts each at 30+ pages of code and trying to
> figure out how to explain why smaller and less complex can be better.
>
> And explain it without cussing...
>
> Leam
>
>
> On Wed, May 24, 2017 at 11:29 AM, James Sumners <james.sumners at gmail.com
> <mailto:james.sumners at gmail.com>> wrote:
>
> Scope. While Bash doesn't have any concept of a closure, it is
> sometimes helpful to know that the internally defined function is
> meant to only be used locally within that parent function.
>
> On Wed, May 24, 2017 at 11:22 AM, leam hall <leamhall at gmail.com
> <mailto:leamhall at gmail.com>> wrote:
>
> I see people do this and I'm not sure why. Is there any
> technical advantage to defining a function inside another,
> assuming it could be defined outside and used inside?
>
More information about the Ale
mailing list