OOPs

chaoticset on 2002-02-10T16:18:16

Well, I get the basics; I get basic inheritance, basic object creation, and methods being subroutines.

The thing I'm working on today is the data side of this issue. I'm still very, very fuzzy on how data ends up in an object, but I think I'm on the verge. A few more examples, a little more footling about, and then I'll download something small and OO and try to dissect it.


Data

pudge on 2002-02-11T13:52:52

Data is in an object usually by saving it in the object variable. For example, most people most often use hashrefs as object data structures:

    sub new {
        my $class = shift;
        return bless {}, $class;
    }

Some people will just allow data access via this hash, directly:

    sub new {
        my $class = shift;
        return bless {blargh => 'data'}, $class;
    }

Then I could do my $foo = new Foo; print $foo->{blargh};, but that would be poor OOP design. We'd rather have $foo->method(). So to save data with a method, you can just do:

    sub set {
        my($self, $key, $data) = @_;
        $self->{_data}{$key} = $data;
    }

which gives us $foo->set('blargh', 'data'). And then to retrieve it:

    sub get {
    my($self, $key) = @_;
    return $self->{_data}{$key};
    }

which gives us print $foo->get('blargh'). Or usually better, an accessor method that does both:

    sub blargh {
        my($self, $val) = @_;
        $self->{_data}{blargh} = $val
            if defined $val;
        return $self->{_data}{blargh};
    }

That gives us $foo->blargh('data'); print $foo->blargh;. HTH.

Re:Data

chaoticset on 2002-02-12T08:07:57

I get everything except {_data}. I've never, never seen that before to the best of my recollection. Looking up {_data} came up blank in _Bookshelf_.

So that I can look it up, what's that called?

Re:Data

pudge on 2002-02-12T14:38:22

_foo is a convention for "this is private, don't touch it." So by putting your data in the object hashref under the _data key, you are telling people who use the object and inspect its contents that they shouldn't touch that data directly, but access it via the published API.