Adam Jarvis
Adam Jarvis

Reputation: 181

Is it better to write many small functions or less large functions?

Currently working on a project, and the thought came to me:

Is it better to write many small functions or less large functions?

I'm writing in PHP if it matters in terms of compilation etc, but in a general sense which is better?

Pseudo code example 1:

// Param i
func example
  switch i
    case x: 
      do func 1
      do func 2
    case y:
      do func 3
      do func 4
  end
end

Pseudo code example 2:

// Param i
func example
  switch i
    case x:
      do stuff from func 1
      do stuff from func 2
    case y:
      do stuff from func 3
      do stuff from func 4
  end
end

Upvotes: 0

Views: 947

Answers (1)

Martin
Martin

Reputation: 22770

If you assess what you're asking these functions to do, are there large blocks of code in a function that have a non-negligable chances of being called but not used?

For instance if you have a function processing an image and acting if PNG or acting if JPG, it's easier to run two functions, one for PNG and one for JPG and simply have a decider function that picks which of these would be called based on the image parameter passed.

One big function

imageloader($imgFile){
    if (image is PNG){
        load image 
        resize image
        output image
    }
    if (image is JPG){
        load image 
        resize image
        output image
    }   
}

Several Smaller Functions

imageloader($imgFile){
    if (image is PNG){
        call pngimg function
    }
    if (image is JPG){
        call jpgimg function
    }
    resize image
    output image
}

pngimg($file) {
    return load PNG image
}

jpgimg($file) {
    return load JPG image
}

The code above now means that if you have another part of your code needing to load a JPG image but not needing to resize it, the you can simply call the imgjpg function , this adds a much higher level of flexibility to your code usage.

Also it depends would there be parts of one function that could be useful in other situations, in which case make that a function in its own right and simply call it from within the running function. running with the Don't Repeat Yourself (DRY) principle of programming.

This is all hypothetical and does depend quite heavily on what your actual code actually is, and what you intend it to be used for and your schedule for code maintenance and onward development in the future.

Upvotes: 2

Related Questions