Getting and Setting and best practise

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jim

    #1

    Getting and Setting and best practise

    Hi guys,

    I have an object which represents an "item" in a CMS "component" where
    an "item" in the most basic form just a field, and a "component" is
    effectively a table.

    "item" objects can be created and then added to "component" objects to
    build up the component definition.

    My dilemma comes in deciding how to read/write data to the "item"
    object.

    I figure I can either:

    1. Use getters and setters (hate the idea of them though)
    2. Use __get and __set which I prefer the idea of from a user
    interface point of view though I understand they take no notice of
    member visibility.
    3. Pass all the required parameters to one function and do all the
    validation there - inflexible, unintuitive and more work in the long
    run in my opinion.

    I'm leaning towards the __get and __set route so I could do:

    $item = new Item('user');

    // could throw exceptions in the functions that do validation
    $item->required = true;
    $item->label = 'User';
    $item->description = 'A description of the item';

    // all validation on the item is done so just add it
    $component->add_item($item );


    Does this make sense? I'm interested in hearing what other methods
    people would choose and why.

    Thanks for any input.

    Jimmy.

  • Steve

    #2
    Re: Getting and Setting and best practise

    | 2. Use __get and __set which I prefer the idea of from a user
    | interface point of view though I understand they take no notice of
    | member visibility.

    plus, the only get called when the caller makes reference to an interface
    that does NOT exist on your object. you cannot for instance, expect to run
    code that handles someone setting $obj->foo (which let's say is
    valid)...__set will only be called when someone tries $obj->Foo or
    $obj->fooo or any other misspelling. afaicr.

    | I'm leaning towards the __get and __set route so I could do:
    |
    | $item = new Item('user');
    |
    | // could throw exceptions in the functions that do validation
    | $item->required = true;
    | $item->label = 'User';
    | $item->description = 'A description of the item';

    not using __set or __get. these vars would simply, and quite happily take
    the value of whatever the rhs threw them. perhaps, with enough
    encouragement, future versions of php will have built in get/set events for
    lhs assignments instead of just having interface access errors begin by
    triggering __get/set.

    | // all validation on the item is done so just add it
    | $component->add_item($item );

    add_item could/would be the best place to add validation for $item, imo.
    however, you still can't protect $item from someone changing it's values
    after add_item has had it's way with it.

    | Does this make sense? I'm interested in hearing what other methods
    | people would choose and why.

    makes sense. i don't worry about anything but data typing in php < 5. after
    data-typing errors are covered, i validate and throw errors immediately
    before critical operations - saving data, etc.. in 5+, you can type your
    variables, so that's less of a concern. however, i still don't do much
    validation until it becomes critical.

    hth...just mo.


    Comment

    • Jim

      #3
      Re: Getting and Setting and best practise

      Hi Steve,
      | 2. Use __get and __set which I prefer the idea of from a user
      | interface point of view though I understand they take no notice of
      | member visibility.
      >
      plus, the only get called when the caller makes reference to an interface
      that does NOT exist on your object. you cannot for instance, expect to run
      code that handles someone setting $obj->foo (which let's say is
      valid)...__set will only be called when someone tries $obj->Foo or
      $obj->fooo or any other misspelling. afaicr.
      I would have something like a switch statement that made sure the
      variables the user is trying to set are valid and runs the appropriate
      private function to validate. For example, I might define
      "descriptio n" as a property which will then exists in the switch list
      in the __set function which will then in turn call set_description
      which would carry out any validation and store the value in something
      like _description. They only thing I really achieve by doing this is
      avoiding the user having to call set and get functions, I think it's
      worth it though.
      add_item could/would be the best place to add validation for $item, imo.
      however, you still can't protect $item from someone changing it's values
      after add_item has had it's way with it.
      I have to disagree with that. It feels most confortable with me to do
      validation in the Item object, since in my mind the logic and
      behaviour of that object should be contained within itself rather than
      creating a dependency on the component object. I'm open to persuation
      though.

      Thanks,

      Jimmy.

      Comment

      • Steve

        #4
        Re: Getting and Setting and best practise

        | I would have something like a switch statement that made sure the
        | variables the user is trying to set are valid and runs the appropriate
        | private function to validate.

        i understand that. what i'm saying (right from the php docs), is that __set
        is ONLY executed in your class by php when an interface that does NOT EXIST
        as part of your class is accessed. same thing with __get.

        | For example, I might define
        | "descriptio n" as a property which will then exists in the switch list
        | in the __set function which will then in turn call set_description
        | which would carry out any validation and store the value in something
        | like _description. They only thing I really achieve by doing this is
        | avoiding the user having to call set and get functions, I think it's
        | worth it though.

        yes, and it is the *correct* approach since you should be able to scope the
        interfaces as well. HOWEVER PHP DOES NOT SUPPORT THIS. sorry, was i speaking
        loudly? :) in the future, perhaps they will. there are many requests out
        there now for such support.

        | add_item could/would be the best place to add validation for $item, imo.
        | however, you still can't protect $item from someone changing it's values
        | after add_item has had it's way with it.
        |
        | I have to disagree with that. It feels most confortable with me to do
        | validation in the Item object, since in my mind the logic and
        | behaviour of that object should be contained within itself rather than
        | creating a dependency on the component object. I'm open to persuation
        | though.

        given the way you showed $item, i stated my opinion. if you put
        getters/setters on $item, i'd not have suggested otherwise and we'd have no
        dispute. as it is currently in php (esp. earlier versions), you cannot
        guarantee the value of ANY interface variable that is public in scope.
        therefore, i usually only fuss about validation before i'm going to do
        something critical with what the object represents.

        make sense?


        Comment

        • Jerry Stuckle

          #5
          Re: Getting and Setting and best practise

          Jim wrote:
          Hi guys,
          >
          I have an object which represents an "item" in a CMS "component" where
          an "item" in the most basic form just a field, and a "component" is
          effectively a table.
          >
          "item" objects can be created and then added to "component" objects to
          build up the component definition.
          >
          My dilemma comes in deciding how to read/write data to the "item"
          object.
          >
          I figure I can either:
          >
          1. Use getters and setters (hate the idea of them though)
          But it's the right way to go. Among other things, it makes the code
          much easier to maintain in the future.
          2. Use __get and __set which I prefer the idea of from a user
          interface point of view though I understand they take no notice of
          member visibility.
          You can do it - but now you have to validate the parameter - is it an
          actual value? And it will be harder to maintain in the future - more
          code to worry about when you add/delete values. Validation also becomes
          much more complicated.
          3. Pass all the required parameters to one function and do all the
          validation there - inflexible, unintuitive and more work in the long
          run in my opinion.
          >
          About the same as using __set, isn't it?
          I'm leaning towards the __get and __set route so I could do:
          >
          $item = new Item('user');
          >
          // could throw exceptions in the functions that do validation
          $item->required = true;
          $item->label = 'User';
          $item->description = 'A description of the item';
          >
          // all validation on the item is done so just add it
          $component->add_item($item );
          >
          >
          Does this make sense? I'm interested in hearing what other methods
          people would choose and why.
          >
          Thanks for any input.
          >
          Jimmy.
          >
          From the point of clarity, ability to later modify the code, etc., I
          much prefer getters and setters. Sure it means you may have a lot of
          functions - but there won't be the independence on other code you have
          with other ways. It will probably be faster, also.



          --
          =============== ===
          Remove the "x" from my email address
          Jerry Stuckle
          JDS Computer Training Corp.
          jstucklex@attgl obal.net
          =============== ===

          Comment

          • Moot

            #6
            Re: Getting and Setting and best practise

            On Apr 20, 8:39 am, Jim <j...@yahoo.com wrote:
            1. Use getters and setters (hate the idea of them though)
            2. Use __get and __set which I prefer the idea of from a user
            interface point of view though I understand they take no notice of
            member visibility.
            Really? Because I've always found __get and __set to be completely
            *UN*intuitive from a user interface point of view.

            To me, the whole concept and reason for making a class is so that you
            can encapsulate logic and present the user (remember, the user of your
            class isn't the end user, it's you or another programmer) with a clear
            set of "here's what you can do with this object type". Using the
            magic get/set functions means that unless you have intimate knowledge
            of the internal working of the class, you would have *no clue* as to
            what is capable with an object of that class.

            Here's an example:
            Say you and I are working on a web app. You've created a class to
            wrap around a contact in a user's addressbook. I need to get a list
            of phone numbers to call for some salespeople, so I say, "hey, I'll
            use this handy Contact class my buddy made". I create an object, type
            $contact-and...??? My IDE's autocomplete pops up with a few
            functions (save, update, etc...), but how do I get the phone number?
            Is it:
            $contact->phone;
            $contact->phonenumber;
            $contact->phone_num;
            $contact->...
            You get the point.
            Whereas with actual defined get/set functions, it would be very
            intuitive. I'd see getPhoneNum() in the autocomplete and instantly
            know that's what I need to call.

            Yes, it is a lot of extra work to make individual get/set functions,
            and most of them are going to be near identical copy/paste jobs, but
            12 months down the road when you have long since forgotten how
            *exactly* your class works, which will be easier? Digging into the
            class code to figure out which variable names you're supposed to use,
            or letting your IDE's autocomplete pop up and immediately knowing what
            get function to call. Take the extra time up front and you'll save
            headaches down the line.

            --
            Moot

            Comment

            • Steve

              #7
              Re: Getting and Setting and best practise


              "Jerry Stuckle" <jstucklex@attg lobal.netwrote in message
              news:yuadncQAZv YUeLXbnZ2dnUVZ_ uejnZ2d@comcast .com...
              | Jim wrote:
              | Hi guys,
              | >
              | I have an object which represents an "item" in a CMS "component" where
              | an "item" in the most basic form just a field, and a "component" is
              | effectively a table.
              | >
              | "item" objects can be created and then added to "component" objects to
              | build up the component definition.
              | >
              | My dilemma comes in deciding how to read/write data to the "item"
              | object.
              | >
              | I figure I can either:
              | >
              | 1. Use getters and setters (hate the idea of them though)
              |
              | But it's the right way to go. Among other things, it makes the code
              | much easier to maintain in the future.

              actually, no, it doesn't. he wants to use a switch in __set/__get and call
              the appropriate PRIVATE getter/setter. PLUS, in doing so, he'd have
              simplified the object's interface. there is NO difference affecting the
              maintainability or scaling of the object in the future.

              only problem is, __set/__get only works when a *non-existent*
              method/property is getted/setted.

              | 2. Use __get and __set which I prefer the idea of from a user
              | interface point of view though I understand they take no notice of
              | member visibility.
              |
              | You can do it - but now you have to validate the parameter - is it an
              | actual value?

              the parameter is always $value. all he'd have to do in his scenario is take
              the __set value as a variant/non-typed variable. his private setter could
              strongly type the param which would throw errors automatically in php if the
              param type didn't match.

              | And it will be harder to maintain in the future - more
              | code to worry about when you add/delete values. Validation also becomes
              | much more complicated.

              i'm not sure you follow what he's saying, otherwise you'd see that your
              'preferred' getting/setting is identical (though less effective) to how he's
              wanting to implement __set/__get - which is only a middle-man between the
              scopes of public and private. validation still happens in the same
              place...getters/setters (your preference noted)...what changes is that HIS
              getters/setters would have PRIVATE scope and would run automatically and
              with LESS code for the developer and the end consumer. ex.,

              his implementation:

              $foo->bar = 'hello world';
              echo $foo->bar;

              yours:

              $foo->setBar('hell o world');
              echo $foo->getBar();

              to me the consumer, i *prefer* the former. now i think you can imagine what
              the code for the class would be in both scenarios. i can spell that out for
              you too if needed. BOTH would have setBar() and getBar() however...which is
              why i can't see how you derive your 'preference' based on your point of
              contention for said opinion(s).

              | 3. Pass all the required parameters to one function and do all the
              | validation there - inflexible, unintuitive and more work in the long
              | run in my opinion.

              again, the same goes here. and, i'll not flog a dead horse any more than i
              have to.

              | About the same as using __set, isn't it?

              obviously not. consumer get ONE interface to deal with in his scenario.

              | From the point of clarity, ability to later modify the code, etc., I
              | much prefer getters and setters. Sure it means you may have a lot of
              | functions - but there won't be the independence on other code you have
              | with other ways. It will probably be faster, also.

              again, he's not doing away with them. he makes them private and the built-in
              __set/__get takes over publically as the middle-man for the public
              interface. and, as __set/__get ARE built-in, nothing you could script will
              execute any faster. as for 'independence' (i think you mean loose coupling),
              __set/__get of the class passes params to the appropriate private
              getters/setters. since they are part of the same object, there is NOTHING to
              decouple.

              i hate to take the arrows from your quiver, but i just don't think you
              understand the post.

              finally, i must say again. __get/__set only execute from php when a
              non-existent interface is accessed. so, no worries jerry, we're still suck
              with public getters/setters...for now.


              Comment

              • Steve

                #8
                Re: Getting and Setting and best practise


                "Moot" <usenet@mootsof t.comwrote in message
                news:1177085607 .182037.77100@d 57g2000hsg.goog legroups.com...
                | On Apr 20, 8:39 am, Jim <j...@yahoo.com wrote:
                | 1. Use getters and setters (hate the idea of them though)
                | 2. Use __get and __set which I prefer the idea of from a user
                | interface point of view though I understand they take no notice of
                | member visibility.
                |
                | Really? Because I've always found __get and __set to be completely
                | *UN*intuitive from a user interface point of view.

                big question mark here.

                | To me, the whole concept and reason for making a class is so that you
                | can encapsulate logic and present the user (remember, the user of your
                | class isn't the end user, it's you or another programmer) with a clear
                | set of "here's what you can do with this object type". Using the
                | magic get/set functions means that unless you have intimate knowledge
                | of the internal working of the class, you would have *no clue* as to
                | what is capable with an object of that class.

                reason for the big question mark? because there is nothing magic going on
                here. haven't you all programmed in non-scripted languages? here's how they
                implement what the op wants...let's say vb.net:

                private static myBar as string
                public static property bar() as string
                get
                return myBar
                end get
                set(byval value as string)
                ' add some validation
                ' maybe throw some errors
                ' else, if all is well
                myBar = value
                end set
                )

                same with c#, same with c++, etc., etc..

                this would be:

                myClass.bar = 'foo'
                debug.writeline (myClass.bar)

                notice his suggestions encapsulates/protect his variable. all __set/__get
                does is pawn off the public call to private getters/setters...emula ting the
                code above. as for *NO CLUE*...i couldn't disagree more. with both his
                scenario and yours, the caller must know that a setter/getter exists.
                however, his doesn't limit nomanclature... as ALL of your object's interfaces
                must begin with either 'get' or 'set'...in his, you just name a variable
                whatever you want. if you rhs it and he wants it to be read-only, he just
                adds a switch in __get and throws an error.

                so what gives?

                | Here's an example:
                | Say you and I are working on a web app. You've created a class to
                | wrap around a contact in a user's addressbook. I need to get a list
                | of phone numbers to call for some salespeople, so I say, "hey, I'll
                | use this handy Contact class my buddy made". I create an object, type
                | $contact-and...??? My IDE's autocomplete pops up with a few
                | functions (save, update, etc...), but how do I get the phone number?
                | Is it:
                | $contact->phone;
                | $contact->phonenumber;
                | $contact->phone_num;
                | $contact->...
                | You get the point.

                your point is that you want to tailor/limit good coding practices to be
                inline with whatever ide of the week is being used. here's my point...the
                public vars will still show up as interfaces in an ide's autocomplete. if
                you try to write a read-only or read a write-only, guess what...you get an
                error. if php wants to help your ide's autocomplete, then maybe they sould
                work something out...as has been done with php documentor. then you'd be
                able to see the scope, parameters, type, access, etc.. just like in
                non-scripted ide's who autocomplete based on the op's code for this
                suggested practice.

                | Whereas with actual defined get/set functions, it would be very
                | intuitive. I'd see getPhoneNum() in the autocomplete and instantly
                | know that's what I need to call.

                christ...should we now have ide wars to go along with the browser wars? to
                which do we yeild our good coding standards/best practices. oh yes, to
                sacrifice.

                | Yes, it is a lot of extra work to make individual get/set functions,
                | and most of them are going to be near identical copy/paste jobs, but
                | 12 months down the road when you have long since forgotten how
                | *exactly* your class works, which will be easier? Digging into the
                | class code to figure out which variable names you're supposed to use,
                | or letting your IDE's autocomplete pop up and immediately knowing what
                | get function to call. Take the extra time up front and you'll save
                | headaches down the line.

                i don't know that you've done oop in a non-scripted language. none of your
                arguments would make valid sense if you had.


                Comment

                • Jerry Stuckle

                  #9
                  Re: Getting and Setting and best practise

                  Steve wrote:
                  "Jerry Stuckle" <jstucklex@attg lobal.netwrote in message
                  news:yuadncQAZv YUeLXbnZ2dnUVZ_ uejnZ2d@comcast .com...
                  | Jim wrote:
                  | Hi guys,
                  | >
                  | I have an object which represents an "item" in a CMS "component" where
                  | an "item" in the most basic form just a field, and a "component" is
                  | effectively a table.
                  | >
                  | "item" objects can be created and then added to "component" objects to
                  | build up the component definition.
                  | >
                  | My dilemma comes in deciding how to read/write data to the "item"
                  | object.
                  | >
                  | I figure I can either:
                  | >
                  | 1. Use getters and setters (hate the idea of them though)
                  |
                  | But it's the right way to go. Among other things, it makes the code
                  | much easier to maintain in the future.
                  >
                  actually, no, it doesn't. he wants to use a switch in __set/__get and call
                  the appropriate PRIVATE getter/setter. PLUS, in doing so, he'd have
                  simplified the object's interface. there is NO difference affecting the
                  maintainability or scaling of the object in the future.
                  >
                  only problem is, __set/__get only works when a *non-existent*
                  method/property is getted/setted.
                  >
                  | 2. Use __get and __set which I prefer the idea of from a user
                  | interface point of view though I understand they take no notice of
                  | member visibility.
                  |
                  | You can do it - but now you have to validate the parameter - is it an
                  | actual value?
                  >
                  the parameter is always $value. all he'd have to do in his scenario is take
                  the __set value as a variant/non-typed variable. his private setter could
                  strongly type the param which would throw errors automatically in php if the
                  param type didn't match.
                  >
                  | And it will be harder to maintain in the future - more
                  | code to worry about when you add/delete values. Validation also becomes
                  | much more complicated.
                  >
                  i'm not sure you follow what he's saying, otherwise you'd see that your
                  'preferred' getting/setting is identical (though less effective) to how he's
                  wanting to implement __set/__get - which is only a middle-man between the
                  scopes of public and private. validation still happens in the same
                  place...getters/setters (your preference noted)...what changes is that HIS
                  getters/setters would have PRIVATE scope and would run automatically and
                  with LESS code for the developer and the end consumer. ex.,
                  >
                  his implementation:
                  >
                  $foo->bar = 'hello world';
                  echo $foo->bar;
                  >
                  yours:
                  >
                  $foo->setBar('hell o world');
                  echo $foo->getBar();
                  >
                  to me the consumer, i *prefer* the former. now i think you can imagine what
                  the code for the class would be in both scenarios. i can spell that out for
                  you too if needed. BOTH would have setBar() and getBar() however...which is
                  why i can't see how you derive your 'preference' based on your point of
                  contention for said opinion(s).
                  >
                  | 3. Pass all the required parameters to one function and do all the
                  | validation there - inflexible, unintuitive and more work in the long
                  | run in my opinion.
                  >
                  again, the same goes here. and, i'll not flog a dead horse any more than i
                  have to.
                  >
                  | About the same as using __set, isn't it?
                  >
                  obviously not. consumer get ONE interface to deal with in his scenario.
                  >
                  | From the point of clarity, ability to later modify the code, etc., I
                  | much prefer getters and setters. Sure it means you may have a lot of
                  | functions - but there won't be the independence on other code you have
                  | with other ways. It will probably be faster, also.
                  >
                  again, he's not doing away with them. he makes them private and the built-in
                  __set/__get takes over publically as the middle-man for the public
                  interface. and, as __set/__get ARE built-in, nothing you could script will
                  execute any faster. as for 'independence' (i think you mean loose coupling),
                  __set/__get of the class passes params to the appropriate private
                  getters/setters. since they are part of the same object, there is NOTHING to
                  decouple.
                  >
                  i hate to take the arrows from your quiver, but i just don't think you
                  understand the post.
                  >
                  finally, i must say again. __get/__set only execute from php when a
                  non-existent interface is accessed. so, no worries jerry, we're still suck
                  with public getters/setters...for now.
                  >
                  >
                  Oh, I understand exactly what he's saying. But I don't have my head up
                  my ass like you do.

                  --
                  =============== ===
                  Remove the "x" from my email address
                  Jerry Stuckle
                  JDS Computer Training Corp.
                  jstucklex@attgl obal.net
                  =============== ===

                  Comment

                  • Steve

                    #10
                    Re: Getting and Setting and best practise

                    | Oh, I understand exactly what he's saying. But I don't have my head up
                    | my ass like you do.

                    seems all evidence is to the contrary. and your strong, emphatic opinion(s)
                    about the matter just makes your backpeddling even more arduous.

                    :)


                    Comment

                    • Geoff Berrow

                      #11
                      Re: Getting and Setting and best practise

                      Message-ID: <Eu6Wh.31$ku5.2 8@newsfe02.lgaf rom Steve contained the
                      following:
                      >| Oh, I understand exactly what he's saying. But I don't have my head up
                      >| my ass like you do.
                      >
                      >seems all evidence is to the contrary. and your strong, emphatic opinion(s)
                      >about the matter just makes your backpeddling even more arduous.
                      >
                      >:)
                      >
                      I thought you two had *PLONK*ed each other?

                      --
                      Geoff Berrow (put thecat out to email)
                      It's only Usenet, no one dies.
                      My opinions, not the committee's, mine.
                      Simple RFDs http://www.ckdog.co.uk/rfdmaker/

                      Comment

                      • Steve

                        #12
                        Re: Getting and Setting and best practise


                        "Geoff Berrow" <blthecat@ckdog .co.ukwrote in message
                        news:nvth231855 pdqv077al40uqid lb7081ouf@4ax.c om...
                        | Message-ID: <Eu6Wh.31$ku5.2 8@newsfe02.lgaf rom Steve contained the
                        | following:
                        |
                        | >| Oh, I understand exactly what he's saying. But I don't have my head up
                        | >| my ass like you do.
                        | >
                        | >seems all evidence is to the contrary. and your strong, emphatic
                        opinion(s)
                        | >about the matter just makes your backpeddling even more arduous.
                        | >
                        | >:)
                        | >
                        |
                        | I thought you two had *PLONK*ed each other?

                        yes...i was laughing at that too. however i have a highly customized version
                        of oe and have programmed in selective plonking. when i *PLONK*, it's on a
                        per thread basis. when i think someone is a total fuckwit, PLONK!!! makes
                        them invisible to me. while my good friend jerry may get there some day, he
                        still has some good advice from what i've seen. i have other features like
                        aliasing a poster's nym. i may give jerry one...how does 'stucco - can't
                        filter language from sound advice' work?


                        Comment

                        • Moot

                          #13
                          Re: Getting and Setting and best practise

                          On Apr 20, 12:56 pm, "Steve" <no....@example .comwrote:
                          "Moot" <use...@mootsof t.comwrote in message
                          | To me, the whole concept and reason for making a class is so that you
                          | can encapsulate logic and present the user (remember, the user of your
                          | class isn't the end user, it's you or another programmer) with a clear
                          | set of "here's what you can do with this object type". Using the
                          | magic get/set functions means that unless you have intimate knowledge
                          | of the internal working of the class, you would have *no clue* as to
                          | what is capable with an object of that class.
                          >
                          reason for the big question mark? because there is nothing magic going on
                          here. haven't you all programmed in non-scripted languages? here's how they
                          implement what the op wants...let's say vb.net:
                          The word "magic" was not me being cute, it's the actual terminology
                          used in the PHP manual:

                          Quote: "The function names __construct, __destruct (see Constructors
                          and Destructors), __call, __get, __set, __isset, __unset (see
                          Overloading), __sleep, __wakeup, __toString, __set_state, __clone and
                          __autoload are magical in PHP classes."
                          >
                          private static myBar as string
                          public static property bar() as string
                          get
                          return myBar
                          end get
                          set(byval value as string)
                          ' add some validation
                          ' maybe throw some errors
                          ' else, if all is well
                          myBar = value
                          end set
                          )
                          >
                          Yes, I've done plenty of .NET programming, but do you see what you did
                          there? You created a Getter/Setter specifically for the variable
                          MyBar, you didn't rely on a "magic" (again, the *actual term*) method
                          to interpret which private variable you wanted. You specifically
                          defined that to get myBar, you need to call bar().
                          >
                          notice his suggestions encapsulates/protect his variable. all __set/__get
                          does is pawn off the public call to private getters/setters...emula ting the
                          code above.
                          If you're going to have private get/set functions, why not just make
                          them public? Why add the extra layer of redirection?
                          >
                          | Here's an example:
                          | Say you and I are working on a web app. You've created a class to
                          | wrap around a contact in a user's addressbook. I need to get a list
                          | of phone numbers to call for some salespeople, so I say, "hey, I'll
                          | use this handy Contact class my buddy made". I create an object, type
                          | $contact-and...??? My IDE's autocomplete pops up with a few
                          | functions (save, update, etc...), but how do I get the phone number?
                          | Is it:
                          | $contact->phone;
                          | $contact->phonenumber;
                          | $contact->phone_num;
                          | $contact->...
                          | You get the point.
                          >
                          your point is that you want to tailor/limit good coding practices to be
                          inline with whatever ide of the week is being used. here's my point...the
                          public vars will still show up as interfaces in an ide's autocomplete.
                          But since we're debating this, I can assume that we all acknowledge
                          that getter/setter functions in any implementation are far superior to
                          allowing the user to access the variable directly, so there should be
                          no public variables visible to the user. Internal object variables
                          should always be wrapped in some kind of get/set function.
                          >
                          | Whereas with actual defined get/set functions, it would be very
                          | intuitive. I'd see getPhoneNum() in the autocomplete and instantly
                          | know that's what I need to call.
                          >
                          christ...should we now have ide wars to go along with the browser wars? to
                          which do we yeild our good coding standards/best practices. oh yes, to
                          sacrifice.
                          >
                          Okay, I see that my mentioning an IDE as an analogy went right over
                          your head. It was a liberty I took to make the example easier, but I
                          see that I need to be more specific for you. Say you write a class
                          that I later want to use. We'll look at it as if you've done it 3
                          different ways:
                          A - you use the __get/__set methods to allow the user to access
                          private variables
                          B - you use the __get/__set methods to allow the user to access
                          private variables by going through a private getter/setter function
                          C - you make seperate getter/setter functions for each private
                          variable
                          Now, to know how to use that class (and, so you don't get snippy, I'll
                          code in Notepad for the sake of this argument), I have to:
                          A - go to the __get function and examine the code (including any if/
                          else or switch conditional logic there may be) to determine what X to
                          call so that it will return me Y
                          B - same as A, only now I find that X points me to Z, which returns me
                          Y
                          C - find the appropriate getX function

                          Maybe in a small class this concept is trivial, but any decently sized
                          class using __get is eventually going to end up being full of
                          conditional switching. Also, if I've been a good little programmer
                          and set up my code for auto-documentation generation, then the
                          generated interface for the object will show all getter/setter
                          functions, but will completely ignore any conditional switching
                          located inside of a __get function.
                          | Yes, it is a lot of extra work to make individual get/set functions,
                          | and most of them are going to be near identical copy/paste jobs, but
                          | 12 months down the road when you have long since forgotten how
                          | *exactly* your class works, which will be easier? Digging into the
                          | class code to figure out which variable names you're supposed to use,
                          | or letting your IDE's autocomplete pop up and immediately knowing what
                          | get function to call. Take the extra time up front and you'll save
                          | headaches down the line.
                          >
                          i don't know that you've done oop in a non-scripted language. none of your
                          arguments would make valid sense if you had.
                          Here's my main point: __get allows you to make your class dynamic in
                          that you can call $obj->anything and let the class figure out what
                          that "anything" means. That's all fine and dandy for the person
                          writing the class, and often makes their life easier. But you don't
                          code OOP for yourself, you code it for the person using the objects,
                          whether that be you or a team of a dozen other programmers. When you
                          make your class able to accept "anything", then how does the user know
                          that $obj->foo is allowed, while $obj->bar is undefined? They don't,
                          unless they open up your code to figure out what the heck you were
                          thinking when you wrote it.

                          Bottom line: the __get/__set functions enable developers to hide the
                          interface to the object INSIDE of the object. Since the interface is
                          how you are expected to interact with an object, it needs to be fully
                          exposed and visible to the outside user. The only way to do this is
                          with publicly visible getter/setter functions

                          - Moot

                          Comment

                          • Steve

                            #14
                            Re: Getting and Setting and best practise

                            "Moot" <usenet@mootsof t.comwrote in message
                            news:1177091647 .851097.10880@y 80g2000hsf.goog legroups.com...
                            | On Apr 20, 12:56 pm, "Steve" <no....@example .comwrote:
                            | "Moot" <use...@mootsof t.comwrote in message
                            | | To me, the whole concept and reason for making a class is so that you
                            | | can encapsulate logic and present the user (remember, the user of your
                            | | class isn't the end user, it's you or another programmer) with a clear
                            | | set of "here's what you can do with this object type". Using the
                            | | magic get/set functions means that unless you have intimate knowledge
                            | | of the internal working of the class, you would have *no clue* as to
                            | | what is capable with an object of that class.
                            | >
                            | reason for the big question mark? because there is nothing magic going
                            on
                            | here. haven't you all programmed in non-scripted languages? here's how
                            they
                            | implement what the op wants...let's say vb.net:
                            |
                            | The word "magic" was not me being cute, it's the actual terminology
                            | used in the PHP manual:
                            | http://us2.php.net/manual/en/language.oop5.magic.php
                            | Quote: "The function names __construct, __destruct (see Constructors
                            | and Destructors), __call, __get, __set, __isset, __unset (see
                            | Overloading), __sleep, __wakeup, __toString, __set_state, __clone and
                            | __autoload are magical in PHP classes."

                            let's just say they are *reserved* words as all other language constructs
                            have. however, *those* are all built-in to php and are a construct by which
                            all must abide. using getters/setters truly IS magic. as i said earlier,
                            setting a property in your example would mean that all properties have
                            associated getProperty/setProperty (for transparency). the preamble
                            (get/set) is a construct of your own making and you require it as a
                            construct yourself.

                            using __set/__get, were it to work the way the op thinks is does, let's you
                            name a property *ANYTHING* and your private getters/setters can be named
                            *ANYTHING*...fu rther, it completely decouples special knowledge about your
                            home-brewed construct of getProperty/setProperty (no matter how commonly
                            used by others).

                            i'm not trying to argue with you here. i'm trying to be as technically
                            accurate as possible.

                            | >
                            | private static myBar as string
                            | public static property bar() as string
                            | get
                            | return myBar
                            | end get
                            | set(byval value as string)
                            | ' add some validation
                            | ' maybe throw some errors
                            | ' else, if all is well
                            | myBar = value
                            | end set
                            | )
                            | >
                            |
                            | Yes, I've done plenty of .NET programming, but do you see what you did
                            | there? You created a Getter/Setter specifically for the variable
                            | MyBar, you didn't rely on a "magic" (again, the *actual term*) method
                            | to interpret which private variable you wanted. You specifically
                            | defined that to get myBar, you need to call bar().
                            |
                            | >
                            | notice his suggestions encapsulates/protect his variable. all
                            __set/__get
                            | does is pawn off the public call to private getters/setters...emula ting
                            the
                            | code above.
                            |
                            | If you're going to have private get/set functions, why not just make
                            | them public? Why add the extra layer of redirection?

                            well, you may want to have mixed scopes on properties - private set/ public
                            get. you may want to have a setter ONLY IN YOUR CLASS so that the validation
                            (which may refer to private members) can be handled uniformly
                            (self::property Setter). and since you can't truly overload in php, there's
                            no way to have a public setter and a private setter at the same time - both
                            doing different things. that means you're stuck adding more magic
                            nomanclature for the private setter. the other way though, you can have a
                            public setter AND a private setter, calling them what you will.

                            plus, it is a hugely transparent operation for the developer. forget that
                            they don't have to know your prefixing the property with get/set. there is
                            less to code. as i showed,

                            $foo->bar = 'hello world';
                            echo $foo->bar;

                            much neater to me. on the back-end, my class is more uniformly defined: one
                            section defines the interfaces, the next with their private getters/setters,
                            and then finally ONE place where each getter/setter is utilized and where
                            the bulk of simple data validation would occur...leaving the getters/setters
                            to simply focus on the business logic rather than both.

                            | your point is that you want to tailor/limit good coding practices to be
                            | inline with whatever ide of the week is being used. here's my
                            point...the
                            | public vars will still show up as interfaces in an ide's autocomplete.
                            |
                            | But since we're debating this, I can assume that we all acknowledge
                            | that getter/setter functions in any implementation are far superior to
                            | allowing the user to access the variable directly, so there should be
                            | no public variables visible to the user. Internal object variables
                            | should always be wrapped in some kind of get/set function.

                            for ANY property to be set, you HAVE TO HAVE a getter and setter. what we're
                            talking about is having php allow us to detect the event and validate the
                            rhs value being assigned to the property.

                            as for 'is it a good idea to let users directly massage properties?'... SURE
                            IT IS. it just depends on what you're doing with the information and how you
                            are going to validate it, if at all. using NEVER is a strong word. i have a
                            ton of singleton's that are all public static variables. the methods on the
                            object are what are used in most of those classes. gi == go...plus i tell
                            them if anything is amiss with properties when they are used. that too could
                            be advantagous as well. think of a setter/getter on an obj in a loop. were
                            validation going on behind each get/set and the loop happened many times,
                            THAT could be a huge lag on the cpu. however validation when needed means
                            the final value of the property would be analyzed only after the
                            loop...speeding things up much quicker.

                            | >
                            | | Whereas with actual defined get/set functions, it would be very
                            | | intuitive. I'd see getPhoneNum() in the autocomplete and instantly
                            | | know that's what I need to call.
                            | >
                            | christ...should we now have ide wars to go along with the browser wars?
                            to
                            | which do we yeild our good coding standards/best practices. oh yes, to
                            | sacrifice.
                            | >
                            |
                            | Okay, I see that my mentioning an IDE as an analogy went right over
                            | your head. It was a liberty I took to make the example easier, but I
                            | see that I need to be more specific for you. Say you write a class
                            | that I later want to use. We'll look at it as if you've done it 3
                            | different ways:
                            | A - you use the __get/__set methods to allow the user to access
                            | private variables
                            | B - you use the __get/__set methods to allow the user to access
                            | private variables by going through a private getter/setter function
                            | C - you make seperate getter/setter functions for each private
                            | variable
                            | Now, to know how to use that class (and, so you don't get snippy, I'll
                            | code in Notepad for the sake of this argument), I have to:
                            | A - go to the __get function and examine the code (including any if/
                            | else or switch conditional logic there may be) to determine what X to
                            | call so that it will return me Y
                            | B - same as A, only now I find that X points me to Z, which returns me
                            | Y
                            | C - find the appropriate getX function

                            there is NO conditional stuff going on in __set/__get. it should contain a
                            switch that calls the appropriate private getter/setter, passing along its
                            arguments.

                            now, you're in the EXACT SAME delima as if we used PUBLIC getters/setters.
                            so, your point here becomes? that you have to look at the switch to see what
                            the private getter/setter name is? if that's the case, just have the law of
                            the land be the same...everythi ng in a class the returns a prop value begins
                            with 'get' and those that set prop values begin with 'set'. but, again
                            you've made no real point here...that i can see.


                            | Maybe in a small class this concept is trivial, but any decently sized
                            | class using __get is eventually going to end up being full of
                            | conditional switching. Also, if I've been a good little programmer
                            | and set up my code for auto-documentation generation, then the
                            | generated interface for the object will show all getter/setter
                            | functions, but will completely ignore any conditional switching
                            | located inside of a __get function.

                            you make a lot of assumptions here, none of which you can back up. the
                            switch is how it is programmed. if you want to complicate the mechanism
                            beyond what i've described, then, yes, it could get ugly. however, my idea
                            of the switch is mearly to act as a stub to which is passes information to
                            the appropriate 'in/out' box.

                            are you simplifying here again? you literally mean this time that we are so
                            sacrifice solid best practices - not for an ide this time - for an
                            'auto-documentation' generator? my former comments on this frivolity apply
                            here as well...so i'll leave it at that.

                            | | Yes, it is a lot of extra work to make individual get/set functions,
                            | | and most of them are going to be near identical copy/paste jobs, but
                            | | 12 months down the road when you have long since forgotten how
                            | | *exactly* your class works, which will be easier? Digging into the
                            | | class code to figure out which variable names you're supposed to use,
                            | | or letting your IDE's autocomplete pop up and immediately knowing what
                            | | get function to call. Take the extra time up front and you'll save
                            | | headaches down the line.
                            | >
                            | i don't know that you've done oop in a non-scripted language. none of
                            your
                            | arguments would make valid sense if you had.
                            |
                            | Here's my main point: __get allows you to make your class dynamic in
                            | that you can call $obj->anything and let the class figure out what
                            | that "anything" means. That's all fine and dandy for the person
                            | writing the class, and often makes their life easier. But you don't
                            | code OOP for yourself, you code it for the person using the objects,
                            | whether that be you or a team of a dozen other programmers. When you
                            | make your class able to accept "anything", then how does the user know
                            | that $obj->foo is allowed, while $obj->bar is undefined? They don't,
                            | unless they open up your code to figure out what the heck you were
                            | thinking when you wrote it.

                            if you make $foo a PUBLIC var then even your ide's autocomplete will pick
                            that up. if it ties into php documentor, then your comments can have the
                            autocomplete state scope, type, etc., etc. as i've said before.

                            what the op wants to do IS define $foo, BUT want's php to let him handle
                            (with __get/__set) $foo when it is on then lhs or rhs of an operation.
                            again, i don't see you have a point. do you think if you gave some
                            psuedo-code here that is would help me get on the same page from which
                            you're reading?

                            | Bottom line: the __get/__set functions enable developers to hide the
                            | interface to the object INSIDE of the object. Since the interface is
                            | how you are expected to interact with an object, it needs to be fully
                            | exposed and visible to the outside user. The only way to do this is
                            | with publicly visible getter/setter functions

                            no, the interface is PUBLIC. what we're hiding and NOT requiring the user to
                            know is the NAME of our PRIVATE getters/setters. they simply use the
                            interface either on the lhs or the rhs...making the object's consumption
                            easier and more decoupled. so NO, 'the only way to do this is' NOT JUST
                            'with publicly visible getter/setter functions'.

                            that's the bottom line, imo.


                            Comment

                            • Steve

                              #15
                              Re: Getting and Setting and best practise

                              || private static myBar as string
                              || public static property bar() as string
                              || get
                              || return myBar
                              || end get
                              || set(byval value as string)
                              || ' add some validation
                              || ' maybe throw some errors
                              || ' else, if all is well
                              || myBar = value
                              || end set
                              || )
                              || >
                              ||
                              || Yes, I've done plenty of .NET programming, but do you see what you did
                              || there? You created a Getter/Setter specifically for the variable
                              || MyBar, you didn't rely on a "magic" (again, the *actual term*) method
                              || to interpret which private variable you wanted. You specifically
                              || defined that to get myBar, you need to call bar().

                              __set is a reserved word as is __get...nothing bad about it.

                              what i think you fail to understand here is that we are getting the same
                              result as the above doing this:

                              <?
                              class foo
                              {
                              public static $bar = '';
                              public static $fighter = '';
                              private function __construct()
                              {
                              // uh oh...is this magic? lol
                              }
                              function __get(...)
                              {
                              switch (var name)
                              {
                              case 'bar' : return self::getBar();
                              break;
                              case 'fighter' : return self::getFighte r();
                              break;
                              default : throw an error here;
                              }
                              }
                              function __set(...)
                              {
                              switch (var name)
                              {
                              case 'bar' : self::setBar(__ set's value param);
                              break;
                              case 'fighter' : self::setFighte r(__set's value param);
                              break;
                              default : throw an error here;
                              }
                              }
                              private function getBar(){ return self::$bar; }
                              private function getFighter{ return self::$fighter; }
                              private function setBar($params)
                              {
                              // validate
                              // if not good, throw an error
                              // else
                              self::$bar = $params;
                              }
                              private function setFighter($par ams)
                              {
                              // validate
                              // if not good, throw an error
                              // else
                              self::$fighter = $params;
                              }
                              }
                              ?>

                              so, how is this different than vb's get/set other than php give ONE place to
                              handle it (__get/__set). you'd just prefer the gets/sets would be grouped
                              together with the property def? guess what, it is php...a scripting
                              language. we don't get properties. we have scoped variables and functions.
                              that's all.

                              at least this functionality would make php seem more like an oop instead of
                              a hacked simulation...us ing getSomething or setSomething. i wonder what
                              other languages would use? in english both get/set are short. however in
                              most other languages, they both are quite long. :) this technique handles
                              that too, since you don't have to fuck with anything.


                              Comment

                              Working...