我什么时候应该中断一个函数? [英] When should I break a function?

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

问题描述

将长函数拆分为主函数和辅助函数是明智之举.

Its prudent to break a long function into a chief function and helper functions.

我知道模块外部只有主函数会被调用,但它的长度可能会令人生畏.

I know that the outside the module only chief function will be called, but its long length may prove to be intimidating.

教科书对行数有限制,但我觉得这太死板了.

Textbooks put a limit on the number of lines, but I feel that this is too rigid.

附言我正在用 Python 编程,需要处理传入的消息.该函数返回一个包含消息的元组,但采用 Python 的内部数据类型.因此,您可以看到每种消息类型的独立代码.

P.S. I am programming in Python and need to process incoming, messages. The function returns a tuple containing the message but in Python's internal data types. So you can see somewhat independent code for each message type.

重复问题

什么时候函数过长?

推荐答案

我认为您需要从问题的另一端着手解决这个问题.自下而上思考.确定尽可能小的工作单元,并开始以这种方式编写代码.当您自上而下编码并且不保持结构化方法时,您只会遇到意大利面条式代码问题.

I think you need to go about this from the other end of the problem. Think bottom-up. Identify small units of work, as small as possible, and start composing your code that way. You will only run into spaghetti-code issues when you code top-down and don't keep a structured approach.

如果您已经有意大利面条式代码并且需要重构,那么您几乎必须重新开始.分解现有的意大利面条式代码可能比重写它的工作量更大,结果可能不会那么好.

If you already have spaghetti code and need to refactor, you pretty much have to start over. It is probably more work to break up existing spaghetti code than to rewrite it, and the result may not be as good.

我也不认为一个方法中的代码行数应该有一个硬性数字,但是编写好的代码不会有方法在较低层超过 5 到 10 行,在底层超过 20 到 30 行业务逻辑.为您提供某种指标.

I don't think there should be a hard number for the lines of code in a method either, but well written code does not have methods with more than 5 to 10 lines in the lower layers, and 20 to 30 lines in the business logic. To give you some kind of metric.

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

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