Classes / Functions / Autonomy

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

    #1

    Classes / Functions / Autonomy

    Hi,

    I have a couple of questions. If you don't mind. Sorry, I do get a bit
    wordy at times. First one just throws some thoughts around hoping for
    answers :-)

    1) Anyone got a theory on the usage of PHP Classes rather than an actual
    technical guide? I've seen loads of things that show how to put together
    a class, but without actually necessarily saying why you'd want to use a
    class over say a separate file of functions or explaining:

    Class someclass {
    var $WhyUseVars;
    var $Something;

    function somefunction ($OrParameters) {
    $this->Something = result;
    return $OrReturnHere
    }
    }

    I mean, should you pass parameters into the function, or set the
    variable properties of the class? Return a value from a function, or set
    another variable?

    What are the advantages? Which way is correct?

    I start thinking, if you start using properties to pass information in
    and out, it's going to get very complicated and messy with properties
    that have no real useful purpose.

    But then if you have one function that relies on another function, there
    is the danger of getting variables floating around from one place to the
    other.

    eg, I pass in a code to function1. Function1 doesn't use that code, but
    passes it onto Function2 in order to perform a lookup and return
    readable information to Function1.

    Of course, then I come up with the thought, that I might want to use the
    second function outside of the first function, but I've written the
    second function in such a way that it can only be called from the first
    function.

    2) I like minimalism and trying to keep things simple as possible,
    without having to remember that in order to use a function I need to
    pass it a number of the variables from the webpage or hardcoded in my
    config.php file. ie, I want to give a function a certain amount of
    autonomy - if it wants a constant in my file, it should get it itself.
    Of course when I first started out, I was using globals.

    Anything better?

    Maybe I could just have a "SiteParameters " class, create a new instance,
    and get the information that way?

    Im not sure what the best way is, I know I just want to avoid needless
    repetition, keep things simple, and avoid the situation where Im passing
    the same information in chained function calls.

    Cheers
    simon
  • Rik

    #2
    Re: Classes / Functions / Autonomy

    Simon Dean wrote:
    Hi,
    >
    I have a couple of questions. If you don't mind. Sorry, I do get a bit
    wordy at times. First one just throws some thoughts around hoping for
    answers :-)
    >
    1) Anyone got a theory on the usage of PHP Classes rather than an
    actual technical guide? I've seen loads of things that show how to
    put together a class, but without actually necessarily saying why
    you'd want to use a class over say a separate file of functions or
    explaining:
    I mean, should you pass parameters into the function, or set the
    variable properties of the class? Return a value from a function, or
    set another variable?
    What are the advantages? Which way is correct?
    <snip even more>

    Well, using classes/objects can be a great way to group values/functions,
    but it's mostly a matter of taste. It highly depends on the actual objective
    wether the OO way is the way to go, or just use functional programming.

    One thing I do realize after toying with OO programming for a while now:
    It's a hell of a lot easier to maintain/change parts of the program, and you
    don't have to keep track of your variables as religiously as in functional
    programming, as they're neatly organized in an object that you can destroy
    in one go, and they will never interfere with the rest of the script.
    2) I like minimalism and trying to keep things simple as possible,
    without having to remember that in order to use a function I need to
    pass it a number of the variables from the webpage or hardcoded in my
    config.php file. ie, I want to give a function a certain amount of
    autonomy - if it wants a constant in my file, it should get it itself.
    Of course when I first started out, I was using globals.
    >
    Anything better?
    Constants? If they're statical all the time I'd think this is better.
    Constants are freely available in functions without explicitly making them
    global. Also, constants defined in functions are automatically global for
    the rest of the script/classes/objects/functions.

    I normally have an ini-file for different project with similar code, and at
    the start of the script:
    $settings = parse_ini_file( "settings.ini") ;
    foreach($setten gs as $key =$value){
    define($key,$va lue);
    }
    Maybe I could just have a "SiteParameters " class, create a new
    instance, and get the information that way?
    Which would result in first making this class global, then getting the value
    out of it. I don't think this is such a good idea.

    Grtz,
    --
    Rik Wasmus


    Comment

    • Simon Dean

      #3
      Re: Classes / Functions / Autonomy

      Rik wrote:
      Simon Dean wrote:
      >>I mean, should you pass parameters into the function, or set the
      >>variable properties of the class? Return a value from a function, or
      >>set another variable?
      >
      >>What are the advantages? Which way is correct?
      >
      <snip even more>
      >
      Well, using classes/objects can be a great way to group values/functions,
      but it's mostly a matter of taste. It highly depends on the actual objective
      wether the OO way is the way to go, or just use functional programming.
      Ok, so, what's better to use, function parameters, or class
      attributes/properties? When is the most appropriate times to use them?

      One thing I do realize after toying with OO programming for a while now:
      It's a hell of a lot easier to maintain/change parts of the program, and you
      don't have to keep track of your variables as religiously as in functional
      programming, as they're neatly organized in an object that you can destroy
      in one go, and they will never interfere with the rest of the script.
      Surely that's the idea of functions too? In that you pass data into it,
      and get something returned.

      >>2) I like minimalism and trying to keep things simple as possible,
      >>without having to remember that in order to use a function I need to
      >>pass it a number of the variables from the webpage or hardcoded in my
      >>config.php file. ie, I want to give a function a certain amount of
      >>autonomy - if it wants a constant in my file, it should get it itself.
      >>Of course when I first started out, I was using globals.
      >>
      >>Anything better?
      >
      >
      Constants? If they're statical all the time I'd think this is better.
      Hrm, Im thinking of things like Database Name, Highlight Colours, I even
      went anal at one point and stored a URL that would retrieve info from a
      database. Why i didn't do it all in the database to begin with I don't
      know. Call me lazy.
      Constants are freely available in functions without explicitly making them
      global. Also, constants defined in functions are automatically global for
      the rest of the script/classes/objects/functions.
      >
      I normally have an ini-file for different project with similar code, and at
      the start of the script:
      $settings = parse_ini_file( "settings.ini") ;
      foreach($setten gs as $key =$value){
      define($key,$va lue);
      }
      >
      >
      >>Maybe I could just have a "SiteParameters " class, create a new
      >>instance, and get the information that way?
      >
      Which would result in first making this class global, then getting the value
      out of it. I don't think this is such a good idea.
      >
      So I couldn't do, oh, say:

      Class Parameters {
      var bgColor;
      var fgColor;
      var dbName;

      function Parameters() {
      $this->bgColor="#FFFF FF";
      $this->fgColor="#0000 00";
      $this->dbName="DB123" ;
      }
      }

      // and then

      Class Page {
      function Open() {
      $Parameters = new Parameters;
      OpenDatabase($P arameters->dbName);
      }
      }


      If I can do this, then I guess Im doing something wrong, Im cheating,
      and Im using something which makes all my declarations global?

      Before I start doing anything major, I have a real intent to do things
      the right way.

      Ta
      Simon

      Comment

      • mootmail-googlegroups@yahoo.com

        #4
        Re: Classes / Functions / Autonomy

        Simon Dean wrote:
        1) Anyone got a theory on the usage of PHP Classes rather than an actual
        technical guide? I've seen loads of things that show how to put together
        a class, but without actually necessarily saying why you'd want to use a
        class over say a separate file of functions or explaining:
        >
        It seems you are thinking of a class as nothing more than a collection
        of variables and functions. The trick is that, even though that's all
        they are, you aren't supposed to think of them that way. A class
        represents an Object, a tangible thing with associated data and
        functionality. It may just be a pile of functions, but they are
        functions that, together, represent something bigger.

        For example, I could reduce myself to a handful of variables and
        functions. I have a name, address, occupation, and I can go to the
        store to buy groceries. If I just put all of those variables and
        functions out there in the main scope, then anyone can use or modify
        them. But, if I instead encapuslate them in a 'matt' object, then if
        anyone wants to know my name or tell me to go to the store, then they
        need to go through ME to do it, which means I can control their access
        appropriately. And this can be beneficial for whoever is doing the
        asking, because instead of having to know who I am, where I left my car
        at, and any number of other things, they just have to say
        matt->buyfood(), and I'll take care of the details.

        On a larger scope, if I have a Item object that represents a field in a
        database, then if I want to save changes to the item, I can call
        item->save(), and don't have to know that it will in turn call
        db->update(foo), which will in turn call mysqldb->update(foo), which
        will in turn call the php functions to interact with a mysql database.
        Abstraction and Encapulation, core principles of Object-Oriented
        Programming, can be very powerful.

        If you really want to understand Object-Oriented Programming, there
        isn't any shortage of papers/articles on the subject.
        >
        I mean, should you pass parameters into the function, or set the
        variable properties of the class? Return a value from a function, or set
        another variable?
        >
        What are the advantages? Which way is correct?
        Neither is incorrect. Just use whatever is approriate for the project
        at hand.
        But, if you call a function and then have to check a property to get
        the result, why not just return the result from the function in the
        first place. If you need to, also set a property so that you can check
        it again later. Don't make more work for yourself than necessary
        >
        Of course, then I come up with the thought, that I might want to use the
        second function outside of the first function, but I've written the
        second function in such a way that it can only be called from the first
        function.
        It is quite common for code to outgrow its original design. Get used
        to refactoring.
        >
        2) I like minimalism and trying to keep things simple as possible,
        without having to remember that in order to use a function I need to
        pass it a number of the variables from the webpage or hardcoded in my
        config.php file. ie, I want to give a function a certain amount of
        autonomy - if it wants a constant in my file, it should get it itself.
        Of course when I first started out, I was using globals.
        I'm not quite sure why, but this concept bothers me. To me, a function
        operates on a set of parameters and then returns a result. If I
        provide those parameters at the time of the call, then I can have a
        reasonable expectation that the results of the function will be
        accurate. However, if I do not provide those parameters, but the
        function instead gets them from some other location, then I have no way
        to know if it is getting the correct values, and thus, can't trust the
        return. This may not be an issue if you are the only one working on
        the project, but if you want your code (and coding-style) to be
        portable to a multi-developer environment, you can't trust that data
        'just sitting there' isn't going to remain untouched.

        Comment

        • Chung Leong

          #5
          Re: Classes / Functions / Autonomy

          Simon Dean wrote:
          I mean, should you pass parameters into the function, or set the
          variable properties of the class? Return a value from a function, or set
          another variable?
          >
          What are the advantages? Which way is correct?
          <subliminal>u se the stack... the stack is your friend... use the
          stack</subliminal>

          Setting properties in lieu of passing arguments is wrong. It makes your
          function non-reentrant, meaning your function cannot be called again
          until it has exited. That's especially problematically in multithreaded
          code. Even in single-threaded code (as is a PHP script) you want to
          avoid it: in a complicate application it's hard to guarantee that a
          function won't end up calling itself.

          <subliminal>sid e effects are evil...</subliminal>

          For example, A::DoAThing() calls B::DoBThing() which in turns calls
          C::DoCThing() and so on. In the midst of this, for some reason,
          K::DoKThing() has to call A::DoAThing(). Now, if K::DoKThing() has to
          modify the object in order to get something to A::DoAThing(), then when
          we return to the beginning of the chain (i.e. when B::DoBThing()
          returns), A::DoAThing() would no longer have the arguments that it had
          started with originally.

          <subliminal>sco ping is good...</subliminal>

          Comment

          • Dikkie Dik

            #6
            Re: Classes / Functions / Autonomy

            (This is going to be a long post)

            Simon Dean wrote:
            Hi,
            >
            I have a couple of questions. If you don't mind. Sorry, I do get a bit
            wordy at times. First one just throws some thoughts around hoping for
            answers :-)
            >
            1) Anyone got a theory on the usage of PHP Classes rather than an actual
            technical guide? ...
            Programming has followed the same path as electronics. When I was born,
            my parents bought a tape recorder. It came with a large piece of paper
            (large enough to cover a whole table) with _the_ electrical scheme. You
            could look for hours at it and still discover new things.

            Just like a GW-basic program. Or a Pascal program. One program that
            contained everything.

            We don't build electronic devices like that anymore. If you open a
            modern tape recorder, you'll see small circuit boards or even encased
            circuits that are plugged together.

            If you want to get a feeling to what an object is, look at a hard disk.
            It has a lot in common with an "object-oriented" object:
            - It has a case that shields its inner (private) parts.
            - It has an interface: a boundary between inside and outside which only
            exposed what needs to be exposed. An interface in the electrical sense
            is a plug. It even has some partial interfaces (interface keyword in
            PHP5): it has a power plug, a data plug, and a "busy" light plug.
            - It has a specific task. This task is so specific that it is totally
            useless without its normal environment. Just like a HtmlElement makes no
            sense outside the HTML DOM.
            - Because it is so specific, it can be tested separately. (in software,
            we call these tests: unit tests)
            - Because is features standard plugs (implements known or general
            interfaces), it can be replaced by something that features the same
            plugs (a RAID device, an optical disk, a storage device based on memory
            cards, etc.)
            >
            Class someclass {
            var $WhyUseVars;
            var $Something;
            >
            function somefunction ($OrParameters) {
            $this->Something = result;
            return $OrReturnHere
            }
            }
            >
            I mean, should you pass parameters into the function, or set the
            variable properties of the class? Return a value from a function, or set
            another variable?
            Here we touch something new: responsibility. Because a class has a
            specific and limited task, it can be held responsible for that task.
            This responsibility can be thoroughly tested (with unit tests) and
            therefore relied upon. Generally, you should not set the properties
            directly, because then these properties are beyond control of the class,
            and then the class looses its responsibility. This means that far more
            code is responsible (or interfering with) the task. In essence, this is
            the same problem as the use of global variables: you never know what the
            state is and when it was set.
            More on responsibility can be found on the net by searching for "Design
            by Contract"
            >
            What are the advantages? Which way is correct?
            >
            I start thinking, if you start using properties to pass information in
            and out, it's going to get very complicated and messy with properties
            that have no real useful purpose.
            This is another reason why you should not use the variables directly.
            Once you separated the inside from the outside (the implementation from
            the interface), you can _optimize_ the inside. Suppose you have a
            collection whose members come from a database. If the class exposed an
            array of member objects directly, The array should be filled beforehand,
            even if only a part of it is used. But if you use an Item() method to
            get to the members, your class now has the choice to load everything in
            advance or on demand. This can have a good impact on performance, but
            does not change the use of the class. This separation between inside and
            outside is called "encapsulation" . The outside only gives access to
            _what_ a class does, and hides the _how_.
            But then if you have one function that relies on another function, there
            is the danger of getting variables floating around from one place to the
            other.
            >
            eg, I pass in a code to function1. Function1 doesn't use that code, but
            passes it onto Function2 in order to perform a lookup and return
            readable information to Function1.
            There need not to be anything wrong with that. In effect, lots of
            coarse-grained functions "delegate" tasks to finer-grained functions.
            Like some coarse-grained classes delegate to finer grained classes.
            >
            Of course, then I come up with the thought, that I might want to use the
            second function outside of the first function, but I've written the
            second function in such a way that it can only be called from the first
            function.
            Then change it. Or better, evolve it. If it is a private method, you can
            make it public. If it relies on a property, you can change that into a
            parameter of the function. No design up front is perfect. And if it is
            perfect today, then it isn't anymore tomorrow. Software grows. Evolves.
            >
            2) I like minimalism and trying to keep things simple as possible,
            without having to remember that in order to use a function I need to
            pass it a number of the variables from the webpage or hardcoded in my
            config.php file. ie, I want to give a function a certain amount of
            autonomy - if it wants a constant in my file, it should get it itself.
            Of course when I first started out, I was using globals.
            Be careful not to give too much responsibility to an object. Should the
            object be responsible for digging for its own data, or should it get the
            data through its constructor? The less you have your objects "break in"
            into its environment, the better it can be understood and maintained.
            The main danger in this is "tight coupling": the objects gets so
            intertwined in other objects or their environment, that they are not
            separate and specific anymore. And therefore cannot be tested separately
            anymore. And therefore cannot be _trusted_ anymore. Think. Should a hard
            disk go find its own power source? If so, could it be used in other
            computers or devices? Definitely not. "Lone cowboy" objects cannot be
            reused and are therefore of little value.
            >
            Anything better?
            >
            Maybe I could just have a "SiteParameters " class, create a new instance,
            and get the information that way?
            That is certainly a way. That object has as responsibility "providing
            access to the state definition of the site". Any object that depends on
            that state, depends on that object. If the state is handled incorrectly,
            you know where to look.
            Such an object is no different from a switchboard or a control panel in
            the electrical sense.
            >
            Im not sure what the best way is, I know I just want to avoid needless
            repetition, keep things simple, and avoid the situation where Im passing
            the same information in chained function calls.
            Please keep the intention of avoiding needless repetition and of
            simplicity. However, some data is often needed and long-lived. The
            database object (or connection), for example, is needed by almost all of
            your database code. So it gets passed around. Nothing wrong with that.

            Best regards

            Comment

            • Jerry Stuckle

              #7
              Re: Classes / Functions / Autonomy

              Simon Dean wrote:
              Hi,
              >
              I have a couple of questions. If you don't mind. Sorry, I do get a bit
              wordy at times. First one just throws some thoughts around hoping for
              answers :-)
              >
              1) Anyone got a theory on the usage of PHP Classes rather than an actual
              technical guide? I've seen loads of things that show how to put together
              a class, but without actually necessarily saying why you'd want to use a
              class over say a separate file of functions or explaining:
              >
              Class someclass {
              var $WhyUseVars;
              var $Something;
              >
              function somefunction ($OrParameters) {
              $this->Something = result;
              return $OrReturnHere
              }
              }
              >
              I mean, should you pass parameters into the function, or set the
              variable properties of the class? Return a value from a function, or set
              another variable?
              >
              What are the advantages? Which way is correct?
              >
              I start thinking, if you start using properties to pass information in
              and out, it's going to get very complicated and messy with properties
              that have no real useful purpose.
              >
              But then if you have one function that relies on another function, there
              is the danger of getting variables floating around from one place to the
              other.
              >
              eg, I pass in a code to function1. Function1 doesn't use that code, but
              passes it onto Function2 in order to perform a lookup and return
              readable information to Function1.
              >
              Of course, then I come up with the thought, that I might want to use the
              second function outside of the first function, but I've written the
              second function in such a way that it can only be called from the first
              function.
              >
              2) I like minimalism and trying to keep things simple as possible,
              without having to remember that in order to use a function I need to
              pass it a number of the variables from the webpage or hardcoded in my
              config.php file. ie, I want to give a function a certain amount of
              autonomy - if it wants a constant in my file, it should get it itself.
              Of course when I first started out, I was using globals.
              >
              Anything better?
              >
              Maybe I could just have a "SiteParameters " class, create a new instance,
              and get the information that way?
              >
              Im not sure what the best way is, I know I just want to avoid needless
              repetition, keep things simple, and avoid the situation where Im passing
              the same information in chained function calls.
              >
              Cheers
              simon
              Simon,

              In addition to what the others have said, let me give you another example.

              As others have said, a class represents an object. An object has state
              (one or more values) and operations you can perform on it.

              For instance - at its most basic level, a variable can be considered a
              type of an object. Take an int for example. It contains one value,
              and you can perform operations on it such as add, subtract, etc.

              A string can also be considered another type ofan object - there you
              have additional functions such as strlen(), strcpy(), etc. No, the
              syntax isn't the same as for a user-defined class. But this is very
              simplistic.

              A floating point number is even more complex. Typically floats are
              stored internally as a number (mantissa) times some power of 2 (base).
              For instance, 40 would be stored as 5,3. That's decoded as 5 times 2 to
              the 3rd power (8). Adding floating point numbers can easily get
              complicated. But the system takes care of all of that for you, so you
              don't have to worry about the internal representation.

              A PHP class is just a user defined object. The difference here is you
              define the state and the operations. The variables in the class are
              meant to hold permanent state - that is, state which extends beyond a
              single member function call, just like the value of an int variable
              extends beyond an arithmetic operation, or the value of a string lasts
              past the strlen() call.

              mootmail's example of a database field is a good one. The variables in
              the class would contain the data from the database. It might be filled
              in by a fetch() call, for instance, and you'll want to keep the data in
              the object so you don't have to someplace else.

              At some future time if you want to change the 'name' value, you can call
              setName() function in the class. And if you want this to be saved in
              the database, you can call update(). The class will take care of
              everything else and you don't have to worry about it- just like you
              don't need to worry about the internal representation of a floating
              point value.

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

              Comment

              • malatestapunk

                #8
                Re: Classes / Functions / Autonomy

                Constants? If they're statical all the time I'd think this is better.
                Constants are freely available in functions without explicitly making them
                global. Also, constants defined in functions are automatically global for
                the rest of the script/classes/objects/functions.
                >
                I normally have an ini-file for different project with similar code, and at
                the start of the script:
                $settings = parse_ini_file( "settings.ini") ;
                foreach($setten gs as $key =$value){
                define($key,$va lue);
                }
                >
                Maybe I could just have a "SiteParameters " class, create a new
                instance, and get the information that way?
                >
                Which would result in first making this class global, then getting the value
                out of it. I don't think this is such a good idea.
                >
                Grtz,
                --
                Rik Wasmus
                Constants are really good for this, as configuration info is statical
                by nature. But you could go with the class as well - there is no need
                to make the configuration object global. You could implement it as
                singleton, and then call MyConfigClass:: getInstance() when you need a
                populated configuration object. I personally prefer doing things this
                way as it keeps everything nicely organized.

                The main thing is to provide methods for getting and setting member
                values and use only these for accessing members, as this gives your
                class the access control. This is especially important in php4, as it
                exposes all members as public.

                As for general OO vs functional programming thing in php, it still
                seems to me more like a matter of taste. Things are different with
                php5, but most servers still run php4. However, I'd go with using
                classes even in functional programming since that keeps similar
                functions neatly organized under a single namespace. You'll appreciate
                this as soon as your code starts to grow in size.

                In my experience, the OO way of doing things proven to be very usefull
                when your requirements change (and they always do). It's was so much
                easier for me to design a large set of small classes while unit-
                testing along the way. Then, when the requirements get updated, it's
                almost trivial to implement the changes and repeat the unit testing
                cycle to make sure everything still works as it should.

                Comment

                • Simon Dean

                  #9
                  Re: Classes / Functions / Autonomy

                  Hi,

                  Thanks for everyones advice so far. Really useful, and have given me
                  some things to think about. I come from a background of VB and DataFlex
                  programming. I guess VB is abhorrent, in that you click a button, the
                  button has to do something else with another control and everything
                  breaks out to the outside :)

                  DataFlex is mainly procedural. You can do a certain amount of OOP
                  programing, but the company I worked for refused. However it really was
                  such a kick I remember, being able to develop these little plug in
                  modules and tools that can be just be used within a program, and they
                  didn't care about the outside environment etc.

                  I used to be such a good programmer, now Im working for a company who
                  writes classes that represents database tables rather than sort of,
                  abstract concepts. So we might have a Persons class that gets passed a
                  SQL String and serves as a Collection of Person classes. And each field
                  is a property of the database table. Seems a bit archaic to me and more
                  complicated than just referring to the database.

                  So Im pushing along with Classes in re-writing one of my websites,


                  I've created a Password class that can do:

                  function Validate($pLogi n, $pPassword) {
                  function MailPassword($p Login, $pPassword, $pEmail) {
                  function GeneratePasswor d() {
                  function ResetPassword($ pLogin, $pEmail) {

                  And only has two variables, an Error code, and an Error string.

                  The reset, will check the login against the email, get a new password
                  from GeneratePasswor d, send it off using MailPassword and voila.

                  But then I had the validate function, and I was wondering whether
                  Session creation should be called from the Validate function, passing
                  the Session object back, or just have the calling program Create a
                  Session Object.

                  Of course the flipside of the coin, I create a new Session Object, ask
                  it validate the password, by getting it to create a new Password object,
                  etc...

                  The answer Im guessing is no. The Password class should not be reliant
                  upon the Session class and vice versa, since I might not want to do
                  anything with Sessions in all instances. The two should be kept distinct
                  and the calling program should handle all function calls itself. Right?

                  So then I find a situation say with Opening a Page, where dependant upon
                  whether Im looking at an item, or say, whether the user is logged in or
                  not (ie we have a session object set), we want to do something
                  different, So I was working on:

                  <?

                  Class Celebrity {


                  var $DName;
                  var $DAge;

                  function Celebrity() {
                  }
                  }

                  Class Page {
                  var $Celebrity;

                  function Page() {
                  }

                  function Open() {
                  if(isset($this->Celebrity)) {
                  echo "Celebrity is set as " . $this->Celebrity->DName;
                  }
                  else {
                  echo "No celebrity is set";
                  }
                  }
                  }

                  This way, my Page class can get all the information it needs from the
                  Celebrity object while generating a page, and it's easy to expand upon.
                  Though it is reliant upon another class? I did the same thing with a
                  Session object, so I could tell it to construct a different menu, and
                  even present the name of the user from the session object for example.

                  Or perhaps it IS better, just to work out what information I actually
                  need, and just pass that across on function parameters?

                  Which way is right?

                  Thanks
                  Simon

                  Comment

                  • mootmail-googlegroups@yahoo.com

                    #10
                    Re: Classes / Functions / Autonomy

                    Simon Dean wrote:
                    I've created a Password class that can do:
                    >
                    function Validate($pLogi n, $pPassword) {
                    function MailPassword($p Login, $pPassword, $pEmail) {
                    function GeneratePasswor d() {
                    function ResetPassword($ pLogin, $pEmail) {
                    >
                    But then I had the validate function, and I was wondering whether
                    Session creation should be called from the Validate function, passing
                    the Session object back, or just have the calling program Create a
                    Session Object.
                    Classes give you the flexibility and power to create very specialized
                    components which can be combined to make a complete system. Think of
                    them as Legos. You have a 2x2 blue piece, and a 4x2 red piece, put
                    them together with a few others, and voila...you have a Tie Fighter.
                    But if they made a one-piece Tie Fighter Lego piece, what are you going
                    to do with it other than make a Tie Fighter...make two?

                    Keep your classes as independent as possible. You may, some time down
                    the road, want to reuse your password class in another project which
                    may not use the Session. Your Validate function should do one thing:
                    Validate. Let some code call it, get a yes or a no, and then figure
                    out what to do with the result itself.
                    >
                    So then I find a situation say with Opening a Page, where dependant upon
                    whether Im looking at an item, or say, whether the user is logged in or
                    not (ie we have a session object set), we want to do something
                    different, So I was working on:
                    >
                    <?
                    >
                    Class Celebrity {
                    >
                    >
                    var $DName;
                    var $DAge;
                    >
                    function Celebrity() {
                    }
                    }
                    >
                    Class Page {
                    var $Celebrity;
                    >
                    function Page() {
                    }
                    >
                    function Open() {
                    if(isset($this->Celebrity)) {
                    echo "Celebrity is set as " . $this->Celebrity->DName;
                    }
                    else {
                    echo "No celebrity is set";
                    }
                    }
                    }
                    >
                    This way, my Page class can get all the information it needs from the
                    Celebrity object while generating a page, and it's easy to expand upon.
                    Though it is reliant upon another class? I did the same thing with a
                    Session object, so I could tell it to construct a different menu, and
                    even present the name of the user from the session object for example.
                    >
                    Or perhaps it IS better, just to work out what information I actually
                    need, and just pass that across on function parameters?
                    >
                    Which way is right?
                    >
                    Again, there is no "right" way to do it. Classes can include/rely
                    upon/use other classes. That kind of thing happens all the time. I
                    would hesitate to use the design you mentioned, though, with your Page
                    class. Is every single page in your project going to need a Celebrity
                    object? If the answer is 'yes', it probably won't be for long. And
                    what happens when you want to do another project and you have to
                    rewrite your Page class to get rid of the Celebrity stuff? A much
                    cleaner design, in my opinion, would be to restrict your Page class to
                    only functions dealing with a generic page (validating the user, etc).
                    You can then create a CelebrityPage class which inherits from the Page
                    class and add in all of your specific code there. That way, to the
                    application, CelebrityPage acts as expected, but if somewhere down the
                    line you need to create a PaparazziPage, you won't have to rewrite the
                    generic page functionality.. .only the specific code.

                    Comment

                    • mootmail-googlegroups@yahoo.com

                      #11
                      Re: Classes / Functions / Autonomy

                      Simon Dean wrote:
                      Which way is right?
                      >
                      I thought of another bit of advise for working with classes.

                      If you want to design a really good class, don't start with the class.
                      I know that seems counter-intuitive, but stick with me, here. Start
                      with the code that will use the class. Pretend as if the class is
                      already implemented and just start calling functions which you would
                      'expect' to be there in order to do what you need to do. After your
                      main program has used the class, then go back and make the class behave
                      like the program expected.

                      A common flaw I have seen in other people's code is that their classes,
                      while they do work, aren't very intuitive or easy to use sometimes.
                      They were written as the programmer thought they should be, and then
                      the code using them was written to accomodate their shortcomings, often
                      by the same developer. Just as a writer often has trouble
                      proof-reading his own writing, it is sometimes hard to see the
                      usability problems in a class when you are the one who wrote it and
                      intimately know it's inner workings.

                      A class isn't just a lump of code. It is a tool which should be easy
                      to learn, intuitive to use, and focused in its functionality. To see
                      well designed classes in action, just look at the .NET framework.
                      Thousands upon thousands of classes which no one would ever hope to be
                      able to memorize, yet a developer can sit down and use pretty much any
                      one of them without looking at documentation first because they were
                      designed from a user's perspective, not the developer's.

                      Comment

                      • Simon Dean

                        #12
                        Re: Classes / Functions / Autonomy

                        mootmail-googlegroups@ya hoo.com wrote:
                        Simon Dean wrote:
                        >
                        >
                        >>I've created a Password class that can do:
                        >>
                        >> function Validate($pLogi n, $pPassword) {
                        >> function MailPassword($p Login, $pPassword, $pEmail) {
                        >> function GeneratePasswor d() {
                        >> function ResetPassword($ pLogin, $pEmail) {
                        >>
                        >
                        >
                        >>But then I had the validate function, and I was wondering whether
                        >>Session creation should be called from the Validate function, passing
                        >>the Session object back, or just have the calling program Create a
                        >>Session Object.
                        >
                        >
                        Classes give you the flexibility and power to create very specialized
                        components which can be combined to make a complete system. Think of
                        them as Legos. You have a 2x2 blue piece, and a 4x2 red piece, put
                        them together with a few others, and voila...you have a Tie Fighter.
                        But if they made a one-piece Tie Fighter Lego piece, what are you going
                        to do with it other than make a Tie Fighter...make two?
                        >
                        Keep your classes as independent as possible. You may, some time down
                        the road, want to reuse your password class in another project which
                        may not use the Session. Your Validate function should do one thing:
                        Validate. Let some code call it, get a yes or a no, and then figure
                        out what to do with the result itself.
                        You won't believe this, but that's exactly what I was thinking. Thinking
                        more than 2 dimensionally too, there's no reason, if I want to tidy
                        things up, that I can't have say a Login class that then relies upon the
                        Password and Session class. The Login process, by definition, validates
                        the passwords and creates the session, but that Password and Session can
                        remain separate.
                        >
                        [snip my celebrity stuff]
                        >>This way, my Page class can get all the information it needs from the
                        >>Celebrity object while generating a page, and it's easy to expand upon.
                        >>Though it is reliant upon another class? I did the same thing with a
                        >>Session object, so I could tell it to construct a different menu, and
                        >>even present the name of the user from the session object for example.
                        >>
                        >>Or perhaps it IS better, just to work out what information I actually
                        >>need, and just pass that across on function parameters?
                        >>
                        >>Which way is right?
                        >>
                        >
                        >
                        Again, there is no "right" way to do it. Classes can include/rely
                        upon/use other classes. That kind of thing happens all the time. I
                        would hesitate to use the design you mentioned, though, with your Page
                        class. Is every single page in your project going to need a Celebrity
                        object? If the answer is 'yes', it probably won't be for long. And
                        what happens when you want to do another project and you have to
                        rewrite your Page class to get rid of the Celebrity stuff?
                        You're reading my mind. Yes, i want to expand this beyond just
                        Celebrities. And I want this to be more than just actors and actresses.
                        So the next logical conclusion, is music, musicians, so I want a band
                        website at some stage with lists of their CD's, all intermingled but
                        subtly separated.

                        Mind you, I've been talking about doing that for several years.

                        Part of the issue for me, is that I need to produce a different menu
                        structure, depending on what the user is doing. So the class needs to
                        know whether a user is logged in, whether they have admin rights, if
                        they are looking at a celebrity, or a band, or a film, I need to present
                        a list of associated links, whether it's "CD Releases and Band Members",
                        or "Filmograph y and Biography". etc.

                        Currently I generate the menu in the Open Page functionand then I
                        generate a path >Celebrity Researcher Administrator Geddy Lee >
                        Biography (for example), and build the appropriate menu.

                        But I guess if this is all split out, there's no reason why I can't say

                        new Page(Title);
                        BuildMenu($Logg edIn, $Administrator, $CelebrityPage, $CelebrityName) ;
                        AddPath("SomePa th");
                        OpenPage();

                        Of course, where I had one line of code originally, OpenPage();, I now
                        stand to get four at least.
                        A much
                        cleaner design, in my opinion, would be to restrict your Page class to
                        only functions dealing with a generic page (validating the user, etc).
                        You can then create a CelebrityPage class which inherits from the Page
                        class and add in all of your specific code there. That way, to the
                        application, CelebrityPage acts as expected, but if somewhere down the
                        line you need to create a PaparazziPage, you won't have to rewrite the
                        generic page functionality.. .only the specific code.
                        >
                        Or there is this I guess :-p

                        So that would be used for maybe interacting with the Celebrity Class I
                        have, or the Papparzi class as you rightly say.

                        Thanks for your help.

                        Simon

                        Comment

                        • Chung Leong

                          #13
                          Re: Classes / Functions / Autonomy

                          mootmail-googlegroups@ya hoo.com wrote:
                          Classes give you the flexibility and power to create very specialized
                          components which can be combined to make a complete system. Think of
                          them as Legos. You have a 2x2 blue piece, and a 4x2 red piece, put
                          them together with a few others, and voila...you have a Tie Fighter.
                          But if they made a one-piece Tie Fighter Lego piece, what are you going
                          to do with it other than make a Tie Fighter...make two?
                          It's easy to build things with Legos. It's much more difficult to
                          create the Lego set in the first place. A final product might take
                          anywhere from one to five years to develop, during which countless
                          prototypes are built, tested, and then fall by the wayside. Something
                          to keep in mind.

                          Comment

                          • Dikkie Dik

                            #14
                            Re: Classes / Functions / Autonomy

                            Thanks for everyones advice so far. Really useful, and have given me
                            some things to think about. I come from a background of VB and DataFlex
                            programming. I guess VB is abhorrent, in that you click a button, the
                            button has to do something else with another control and everything
                            breaks out to the outside :)
                            Why? Just because you can type some code in an event handler, that does
                            not mean that your entire program must reside there. You can do a lot of
                            object-orientation in VB. It is not VB's fault that so few programmers do.
                            I used to be such a good programmer, now Im working for a company who
                            writes classes that represents database tables rather than sort of,
                            abstract concepts. So we might have a Persons class that gets passed a
                            SQL String and serves as a Collection of Person classes. And each field
                            is a property of the database table. Seems a bit archaic to me and more
                            complicated than just referring to the database.
                            Often, I do this as well. My table wrappers abstract the main entities
                            in the storage. These main entities are usually also defined in my
                            object-oriented model, so a mapping is not that bad.
                            The table wrappers's responsibility is the (for me) handling the storage
                            and the storage strategy, without bothering the rest of the program.
                            This strategy can be "greedy" (load as much as you think you need once,
                            in one batch) or "lazy" (on demand) or even a mixture of the two. I
                            wrote more on that in:

                            I've created a Password class that can do:
                            >
                            function Validate($pLogi n, $pPassword) {
                            function MailPassword($p Login, $pPassword, $pEmail) {
                            function GeneratePasswor d() {
                            function ResetPassword($ pLogin, $pEmail) {
                            >
                            And only has two variables, an Error code, and an Error string.
                            I would think more like an organization. Some client wants to enter your
                            website, but is only allowed to do so if the door-keeper has verified
                            your identity. The door-keeper will usually not generate the password
                            himself, and it is the postman that will deliver it.

                            So there are tree objects here:
                            - DoorKeeper
                            - UserAccount or PasswordManager
                            - Mailer (or TemplateMailer)

                            The DoorKeeper needs a username and a password and may return a
                            UserAccount. Now, Doorkeeper could also be constructed with a session
                            value, a cookie value or whatever. It is the DoorKeeper's responsibility
                            to check valid identities. Just like in real life, where more than one
                            document may be a valid identification.

                            The UserAccount holds the user data (is a record wrapper initially), but
                            can accept a request to reset a password. Upon password change, it
                            (perhaps indirectly) informs the password mailer.

                            This password mailer can also be activated by the "forgot password code"

                            The password mailer uses the general mailer to send the notification.
                            During unit testing, you can replace the general mailer with a test
                            double, so you can check that the mail _would_ have been sent, without
                            actually spamming someone.

                            .... <snip...
                            This way, my Page class can get all the information it needs from the
                            Celebrity object while generating a page, and it's easy to expand upon.
                            Though it is reliant upon another class? I did the same thing with a
                            Session object, so I could tell it to construct a different menu, and
                            even present the name of the user from the session object for example.
                            That is up to you. Play with it and see where it gets you. You can
                            always reverse the dependencies: You could instruct a celebrity to
                            "render" itself of a page. In this case, The celebrity object would get
                            a render method, with a page as parameter. If you find the page too
                            specific as parameter, you can define an abstract super class (or
                            interface) "renderer", of which the page inherits.

                            Compare this with your MP3 player. It contains music, but it accepts an
                            audio plug to send the signal to. This audio plug is an interface.
                            Anything that implements that interface will do: headphones, little
                            speakers, the soundcard of your computer, etc. All these devices have an
                            audio input plug, and therefore implement the "AudioPlaye r" interface.

                            Good luck!

                            Comment

                            Working...