什么是间接对象表示法,为什么不好,如何避免呢? [英] What is indirect object notation, why is it bad, and how does one avoid it?

查看:106
本文介绍了什么是间接对象表示法,为什么不好,如何避免呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题几乎是所有内容的总和,但这还是长版本.

The title pretty much sums it up, but here's the long version anyway.

在发布一小段Perl代码后,我被告知要避免使用间接对象表示法,因为它具有多种副作用".该评论引用了以下特定行:

After posting a small snippet of perl code, I was told to avoid indirect object notation, "as it has several side effects". The comment referenced this particular line:

my $some_object = new Some::Module(FIELD => 'value');

因为这是我一直以来的做法,所以为了与时俱进,我问:

As this is how I've always done it, in an effort to get with the times I therefore ask:

  • 这有什么不好的呢? (具体而言)
  • 潜在的(可能是负面的)副作用是什么?
  • 该行应如何重写?

我正要问评论者,但对我而言,这是值得的.

I was about to ask the commenter, but to me this is worthy of its own post.

推荐答案

主要问题是模棱两可.是

The main problem is that it's ambiguous. Does

my $some_object = new Some::Module(FIELD => 'value');

表示在Some::Module包中调用new方法,或者是在当前包中调用new函数,结果是在Some包中调用Module函数给定的参数?

mean to call the new method in the Some::Module package, or does it mean to call the new function in the current package with the result of calling the Module function in the Some package with the given parameters?

即,它可以解析为:

# method call
my $some_object = Some::Module->new(FIELD => 'value');
# or function call
my $some_object = new(Some::Module(FIELD => 'value'));

另一种方法是使用显式方法调用符号Some::Module->new(...).

The alternative is to use the explicit method call notation Some::Module->new(...).

通常,解析器会正确猜测,但是最佳实践是避免歧义.

Normally, the parser guesses correctly, but the best practice is to avoid the ambiguity.

这篇关于什么是间接对象表示法,为什么不好,如何避免呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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