in reply to OOP, ".NET", Perl, and all that

Is it really such a chore to put the initial default value for instance data in the constructor? You have to put it somewhere, and that seems like the logical place to me.

Replies are listed 'Best First'.
Re: Re: OOP,
by hding (Chaplain) on Dec 14, 2001 at 23:43 UTC

    If you have a variety of different constructors, though, it would seem to be possible that two of them might need to specify the same default value for a variable (and it might be impossible to rig things up so that one could get it by invoking the other at some point), so something like this would help keep things in sync if a change ever needed to be made.

      "a variety of different constructors"? I may be a newcomer to OOP, but that's a recipe for disaster unless you factor out the commonalities at the package level and create private methods that do those parts for your various public constructors.

      Another solution, if you absolutely insist on a myriad of monolithic constructor routines (again, these sound like a maintenance nightmare), is to create a package global that holds a default $self to be assigned when you declare my $self the first time in each constructor, and then over-ridden as the parameters are dealt with.
        Think about it this way:
        1. You don't know anything about the internals of the object.
        2. You have been told that the object will take either:
          • a list of values (in a certain order and restrictions on the values)
          • a hash (with a certain set of keys and restrictions on the values)
          • another object like itself
          • another object similar to itself (maybe a parent class?)
        In order to allow for the four completely different ways to construct the object, the object has to have four different constructors. In C++, these would four separate functions with different munged names. In Perl, we'd have one function that may (or may not) branch out into one or more helper functions. The copy constructor, for example, might call the clone() function on the object passed in. (clone() would be used in a similar fashion.)

        ------
        We are the carpenters and bricklayers of the Information Age.

        Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.