在编写Perl模块时,是否必须在所有方法中专门检查对象实例? [英] When writing a Perl module, do I have to specifically check for an object instance in all my methods?

查看:50
本文介绍了在编写Perl模块时,是否必须在所有方法中专门检查对象实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个具有几种方法的模块.让我们考虑一下:

I'm writing a module that has several methods. Let's consider this :

package MyPackage;
sub new {
 ...
}

sub do_your_job {
 ...
}
1;

如何阻止某人像MyPackage->do_your_job而不是$obj->do_your_job那样呼叫do_your_job?我是否需要检入将引用作为第一个参数的每个方法?

What is to stop someone calling do_your_job like MyPackage->do_your_job instead of $obj->do_your_job ? Do I need to check in every method that I'm receiving a reference as the first argument?

推荐答案

否.如果您的模块仅包含最少量的文档,则应该清楚do_your_job是需要在对象上调用的方法.如果有人想用其他方式打电话给他,这是他的错误.

No. If your module features only the most minimal documentation, it should be clear from that that do_your_job is a method that needs to be called on an object. If someone wants to call that in some other way, it's his fault.

当然,您可以检查方法的第一个参数是否是受祝福的对象.但这至少有两个缺点:您会损失一点性能,并且使用的代码实际上无法执行方法名称所承诺的任何事情,会使您的方法变得混乱.

Of course, you could check whether the first parameter to your method is a blessed object. But this has at least two drawbacks: You lose a little bit of performance and you clutter your methods with code that really doesn't do anything promised by the method's name.

这篇关于在编写Perl模块时,是否必须在所有方法中专门检查对象实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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