Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: Re (tilly) 3: Inheriting object data

by archon (Monk)
on Feb 17, 2001 at 03:24 UTC ( [id://59034]=note: print w/replies, xml ) Need Help??

in reply to Re (tilly) 3: Inheriting object data
in thread Inheriting object data

ah, i see. in this example that i cooked up to demonstrate the problem it is not used. in my real program, it is.

the base class has login and password info that all the subclasses use. the base class also has a login method.

the effect i was trying to achieve was to only have to pass the data (login/password) once and have it stored in a core object from which all the derived objects inherited not only its methods, but object data. does that violate OO principles?

  • Comment on Re: Re (tilly) 3: Inheriting object data

Replies are listed 'Best First'.
Re (tilly) 5: Inheriting object data
by tilly (Archbishop) on Feb 17, 2001 at 03:33 UTC
    In your situation I might store the login and password information in global variables in the base class. You can even be clever about it and have the constructor take those globals as default values, but allow someone to override it.

    An alternate approach is to use a has-a relationship. In that case Foo::Bar would not inherit from Foo, but would have a property that was an object of type Foo, and would have a login method like this:

    sub login { my $self = shift; $self->{base_obj}->login(@_); }
      Thanks.. where can I find out more about the has-a relationship? I don't see it in Conway's _Object Oriented Perl_.
      Well, I modified it to use a has-a relationship (I believe) but now I am violating my original desire to only have to pass the hash once, i.e. I will have to pass it for each class I create.

      As far as your first suggestion, I am turned off by the use of global variables that look like they ought to be object properties. (= Do you think this is still a better way than my original design?

        How about something like this? It's encapsulated due to lexical variables and block scope, but you have access to it with accessor methods:
        package Parent; { my ($name, $pass); sub new { my $class = shift; my $self = {}; if (@_) { ($name, $pass) = @_; } @$self{'name', 'pass'} = ($name, $pass); bless($self, $class); } }
        You could add another method in there to reset the name and password. You could store references to $name and $pass in the hash, so updating the parent data is reflected in the children.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://59034]
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (None)
    As of 2024-04-15 12:25 GMT
    Find Nodes?
      Voting Booth?

      No recent polls found