[Israel.pm] Detecting calls for unknown methods in compile time
Shlomi Fish
shlomif at iglu.org.il
Thu Sep 23 07:05:11 PDT 2010
Hi Ronen,
On Thursday 23 September 2010 13:46:55 Ronen Angluster wrote:
> Hello all,
>
first, a few comments about your code.
> please consider the following code:
> ###################################
> package main;
Always add "use strict;" and "use warnings;". Also see:
http://perl-begin.org/tutorials/bad-elements/
> my $x= main::foo->new();
1. my $x = foo->new(); would be enough here.
2. You should start namespaces with an uppercase letter. Namespaces starting
with a lowercase letter are reserved for pragmas.
> $x->bar();
> $x->barx();
>
> package foo;
>
> sub new {
> my $this = shift;
> my $class = ref($this) || $this;
Don't do this:
http://www.stonehenge.com/merlyn/UnixReview/col52.html
Just extract the $class.
Now to answer your question.
> my $self={};
> bless ($self, $class);
> return $self;
> }
>
> sub bar
> {
> my $self = shift;
> print "foo\n";
> }
> #################################
>
> now, executing this code with "perl -cw script.pl" will not produce any
> errors since the call for the reference of "barx" will only
> be evaluated during runtime.
> is there a way to detect such errors in compile time?
First of all, you can sort of cheat and use ->can (see perldoc UNIVERSAL) or
whatever in a BEGIN { ... } block, which -c runs. Otherwise, there cannot be a
way because the class with which a variable is blessed to is not known at
compile-time and may actually change in run-time:
[code]
my $x = OneClass->new(...);
.
.
.
if (int(rand(2)) == 0)
{
$x = CompletelyDifferentClass->new(...);
}
.
.
.
$x->my_method();? # What now?
[/code]
So you need to rely on the run-time exception and your automated tests' suite
to overcome this:
https://docs.google.com/View?id=dcsvntt2_25wpjvbbhk (Strong Typing vs. Strong
Testing).
Regards,
Shlomi Fish
--
-----------------------------------------------------------------
Shlomi Fish http://www.shlomifish.org/
Optimising Code for Speed - http://shlom.in/optimise
<rindolf> She's a hot chick. But she smokes.
<go|dfish> She can smoke as long as she's smokin'.
Please reply to list if it's a mailing list post - http://shlom.in/reply .
More information about the Perl
mailing list