• DarkAri@lemmy.blahaj.zone
    link
    fedilink
    arrow-up
    7
    ·
    1 day ago

    The rule of thumb I use is how likely am I to reuse some part of this code in the future? Also readability. Sometimes I like to just wrap some code in functions to make the code look neater. Other considerations are how often will this function be called? The overhead of calling a function is tiny but if a program is used by millions, everyday for many years, it’s sort of like not littering a bit to make the code a bit more inline. It is kind of nice to be able to mostly see what a piece of code does in a glance other than when it’s just wasteful.

    • kryptonianCodeMonkey@lemmy.world
      link
      fedilink
      arrow-up
      2
      ·
      edit-2
      1 day ago

      Concise readability is usually my goal. Like if I have 12+ lines of code with a loop and some nested conditionals, recursively digging into buried directories, that probably takes a bit of thought to parse. So it is probably is better to move that to a function with a descriptive name like, “size, depth = get_directory_size_and_depth(filepath)”, that way the function name itself serves as it’s own comment/documentation describing what’s being done and, if you don’t really care about how the size and depth is aggregated, it abstracts that process into one line of code in the calling function that the reader can instantly understand without parsing the whole process. That goes doubly so when the function is generic like get_directory_size_and_depth(filepath) would be, and can be put in its own shared utilities file.