dongraa1986 2016-06-30 14:52
浏览 45
已采纳

编写许多小函数或不太大的函数是否更好?

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
  • 写回答

1条回答 默认 最新

  • dourangdz750379 2016-06-30 15:09
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法