什么时候函数太长? [英] When is a function too long?

查看:142
本文介绍了什么时候函数太长?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

35行,55行,100行,300行?当你应该开始把它分开?我问是因为我有一个60行的函数(包括注释),并且正在考虑将它分开。

35 lines, 55 lines, 100 lines, 300 lines? When you should start to break it apart? I'm asking because I have a function with 60 lines (including comments) and was thinking about breaking it apart.

long_function(){ ... }

into:

small_function_1(){...}
small_function_2(){...}
small_function_3(){...}

这些函数不会在long_function之外使用,使更小的函数意味着更多的函数调用等。

The functions are not going to be used outside of the long_function, making smaller functions means more function calls, etc.

你什么时候将一个函数分解成更小的函数?为什么?

When would you break apart a function into smaller ones? Why?


  1. 方法应该只做一个逻辑的事情(考虑功能)

  2. 能够在一个句子中解释方法

  3. 它应该适合您的显示器的高度

  4. 避免不必要的开销...)

  5. 小逻辑函数的单元测试更容易

  6. 检查函数的一部分是否可以被其他类或方法重用

  7. 避免过度的类间耦合

  8. 避免深层嵌套的控制结构

  1. Methods should do only one logical thing (think about functionality)
  2. You should be able to explain the method in a single sentence
  3. It should fit into the height of your display
  4. Avoid unnecessary overhead (comments that point out the obvious...)
  5. Unit testing is easier for small logical functions
  6. Check if part of the function can be reused by other classes or methods
  7. Avoid excessive inter-class coupling
  8. Avoid deeply nested control structures

感谢大家的答案,编辑列表并投票给正确答案我会选择一个;)

Thanks everyone for the answers, edit the list and vote for the correct answer I'll choose that one ;)

我现在用这些想法重构:)

I am refactoring now with those ideas in mind :)

推荐答案

没有真正困难和快速的规则。一般来说,我喜欢我的方法只是做一件事。所以如果它抓取数据,然后做一些数据,然后把它写到磁盘,然后我会拆分出来抓取和写入单独的方法,所以我的main方法只包含做某事。

There's no real hard and fast rules for it. Generally I like my methods to just "do one thing". So if it's grabbing data, then doing something with that data, then writing it to disk then I'd split out the grabbing and writing into separate methods so my "main" method just contains the "doing something".

做某事仍然可以是几行,所以我不确定一些行是否是正确的指标使用:)

That "doing something" could still be quite a few lines though, so I'm not sure a number of lines is the right metric to be using :)

编辑:这是一个单行代码我邮寄周围的工作上周(证明一点..它不是我做一个习惯:)) - 我肯定不会想要50- 60我的方法中的这些坏男孩:D

This is a single line of code I mailed around work last week (to prove a point.. it's not something I make a habit of :)) - I certainly wouldn't want 50-60 of these bad boys in my method :D

return level4 != null ? GetResources().Where(r => (r.Level2 == (int)level2) && (r.Level3 == (int)level3) && (r.Level4 == (int)level4)).ToList() : level3 != null ? GetResources().Where(r => (r.Level2 == (int)level2) && (r.Level3 == (int)level3)).ToList() : level2 != null ? GetResources().Where(r => (r.Level2 == (int)level2)).ToList() : GetAllResourceList();

这篇关于什么时候函数太长?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆