" I've read that post, and that's why I said I would like to hear merlyn's thoughts."
Um, those are merlyn's thoughts. ;) Did you
mean 'my' thoughts? Let's open that can of worms then.
:D
At this point, the whole matter is strictly
opinion. The way i see it, if someone uses one of my
modules incorrectly, they didn't read the POD. That is how
you provide proper instruction on how to use a class.
If i want them to be able to clone a class, i will provide
a clone() method, and more importantly, i will provide POD
that shows them how to instantiate and, if applicable,
clone my objects.
And i do not agree with your two statements being equal.
The main reason is because you have two distinct audiences.
Someone who just uses a program is not required to have
any knowledge of the language, but someone who programs
against that language better have knowledge. Further more,
someone who accesses the constructor on an instantiated
object clearly does not know what they are doing. Unless
we are talking about a factory [method] pattern, the
constructor should be class method, not an instance method.
Try doing this in Java ...
class Foo {
public static void main(String args[]) {
Bar bar = new Bar(42);
System.out.println(bar.foo);
Bar baz = bar.Bar(2112);
System.out.println(baz.foo);
}
}
class Bar {
public int foo;
public Bar(int foo) {
this.foo = foo;
}
}
Does not work. Try Python:
class Bar:
def __init__(self, foo):
self.foo = foo
bar = Bar(42)
print bar.foo
baz = bar.__init__(2112)
print baz.foo
Does not work. Ruby?
class Bar
def kind=(f)
@foo = f
end
def kind
@foo
end
end
bar = Bar.new
bar.kind = 42
print bar.kind
baz = bar.new
baz.kind = 2112
print baz.kind
Does not work. Why? Because in all of these languages,
the constructor is built-in. Perl's 'constructor' is not.
You should not be able to call a
built-in constructor as an instance method. This is one of
the reasons why i do not like to teach OO with Perl, but it
also one of the reasons why i love to program OO with
Perl. Correct me if am wrong, but i believe that Perl6
is going to provide a built-in constructor, called new:
class User;
my ($id, $name, $email);
# look ma, no new!!!
package main;
my $u = User.new('abw', 'Andy Wardley', 'abw@kfs.org');
So, you do what you want. That is what Perl5 is all about.
As long as you know why you are doing what you are doing,
all is well. But i still think trying to prevent someone from "incorrectly" using my Perl class is just plain silly.
However, if you are really paranoid about such things,
try this instead:
package foo;
use strict;
use Carp;
sub new {
my ($class,$id) = @_;
croak "can't call new as instance method" if ref($class);
my $self = {
id => $id || 42,
};
return bless $self,$class;
}
Better to deny them than deceive them. ;)
jeffa
L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
B--B--B--B--B--B--B--B--
H---H---H---H---H---H---
(the triplet paradiddle with high-hat)
|