使现场操作返回对象一个坏主意? [英] Is making in-place operations return the object a bad idea?

查看:123
本文介绍了使现场操作返回对象一个坏主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里主要谈论Python,但我认为这可能适用于大多数语言。如果我有一个可变对象,是一个坏主意,使一个就地操作也返回对象?似乎大多数示例只是修改对象并返回 None 。例如, list.sort

I'm talking mostly about Python here, but I suppose this probably holds for most languages. If I have a mutable object, is it a bad idea to make an in-place operation also return the object? It seems like most examples just modify the object and return None. For example, list.sort.

推荐答案

馊主意。原因是如果现场和非现场操作具有明显相同的输出,则程序员将经常混合就地操作和非现场操作( List.sort() sorted()),并导致难以检测的错误。

Yes, it is a bad idea. The reason is that if in-place and non-in-place operations have apparently identical output, then programmers will frequently mix up in-place operations and non-in-place operations (List.sort() vs. sorted()) and that results in hard-to-detect errors.

就地操作返回自己可以允许你执行方法链接,但是,这是不好的做法,因为你可能会意外地在链中间插入副作用的功能。

In-place operations returning themselves can allow you to perform "method chaining", however, this is bad practice because you may bury functions with side-effects in the middle of a chain by accident.

为了防止这样的错误,方法链应该只有一个具有副作用的方法,并且该函数应该在链的末尾。函数之前的链应该转换输入没有副作用(例如,导航树,切片字符串等)。如果就地操作返回自己,那么程序员被绑定意外地使用它代替返回副本的替代函数,因此没有副作用(再次, List.sort() sorted()),这可能导致难以调试的错误。

To prevent errors like this, method chains should only have one method with side-effects, and that function should be at the end of the chain. Functions before that in the chain should transform the input without side-effects (for instance, navigating a tree, slicing a string, etc.). If in-place operations return themselves then a programmer is bound to accidentally use it in place of an alternative function that returns a copy and therefore has no side effects (again, List.sort() vs. sorted()) which may result in an error that is difficult to debug.

是Python标准库函数总是返回一个副本或返回并且原地修改对象,但是从不修改对象并返回自身的原因。其他Python库如Django也遵循这种做法(见这个非常类似问题关于Django)。

This is the reason Python standard library functions always either return a copy or return None and modify objects in-place, but never modify objects in-place and also return themselves. Other Python libraries like Django also follow this practice (see this very similar question about Django).

这篇关于使现场操作返回对象一个坏主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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