SitePoint Sponsor

User Tag List

Results 1 to 8 of 8
  1. #1
    SitePoint Member
    Join Date
    Jul 2012
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Why use private properties and getter methods vs. using public properties

    I'm trying to get my head wrapped around all the concepts of OOP. I have heard that it is better to use private properties and use getting methods rather then using public properties. It seems like it has the same result but I am trying to understand why one is any better then the other. In the two class samples below I have done it both ways and wanted to see if someone could tell me why the second one would be better then the first one.


    PHP Code:

    class Movie
    {

        public 
    $movie_id
        
    public $movie_name;
        public 
    $rating;
        public 
    $genre;
        public 
    $director;
        
        
        public function 
    getMovie($id)
        {
            
            
    $sql "select * from movie where movie_id = $this->movie_id";
            
    $result mysql_query($sql);
            
    $row mysql_fetch_array($result);
            
    $this->movie_name $row['movie_name'];
            
    $this->rating $row['rating'];
            
    $this->genre $row['genre'];
            
    $this->director $row['director'];
            
        }


    }


    class 
    Movie
    {

        private 
    $movie_id
        
    private $movie_name;
        private 
    $rating;
        private 
    $genre;
        private 
    $director;
        
        
        public function 
    getMovie()
        {
            
            
    $sql "select * from movie where movie_id = $this->movie_id";
            
    $result mysql_query($sql);
            
    $row mysql_fetch_array($result);
            
    $this->movie_name $row['movie_name'];
            
    $this->rating $row['rating'];
            
    $this->genre $row['genre'];
            
    $this->director $row['director'];
            
        }
        
        public function 
    getMovieName()
        {
            return 
    $this->movie_name;
        }
        
        public function 
    getRating()
        {
            return 
    $this->rating;
        }
        
        public function 
    getGenre()
        {
            return 
    $this->genre;
        }
        
        public function 
    getDirector()
        {
            return 
    $this->director;
        }



    If it is easier to show the reason with another sample that is fine, I just thought it might make more sense to me this way.

    Thanks

  2. #2
    Programming Team silver trophybronze trophy
    Mittineague's Avatar
    Join Date
    Jul 2005
    Location
    West Springfield, Massachusetts
    Posts
    17,154
    Mentioned
    190 Post(s)
    Tagged
    2 Thread(s)
    In your simple example, not much difference. And I guess in many cases still not much difference.

    -But-
    What if you wanted to log when a property was set or "got"? Using getters and setters you could easily keep track of things.

  3. #3
    Hosting Team Leader silver trophybronze trophy
    cpradio's Avatar
    Join Date
    Jun 2002
    Location
    Ohio
    Posts
    5,125
    Mentioned
    152 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Mittineague View Post
    In your simple example, not much difference. And I guess in many cases still not much difference.

    -But-
    What if you wanted to log when a property was set or "got"? Using getters and setters you could easily keep track of things.
    To add on, or if you wanted to send back a default value for unset or null properties to present a consistent experience to the user encapsulating or utilizing your object. Another common usage is to indicate that the class is "dirty" meaning, it needs to update the database because someone updated a property using a setter.

  4. #4
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Your first example implies there is no contract with the end user of this class (imagine you work in a team, and you are only there for 3 months).

    This means anyone can purposely, or accidentally do this:

    PHP Code:
    $a = new Movie(23);
    $a->movie_name "Any old crap"
    They could even accidentally do this by extending this class in ways you had not originally imagined.

    Your second example makes it clear that nobody can set movie_name, and the only way to get movie_name is to call the appropriate method.

    What is more, if you or they extend that class then they also cannot gain access to those members without using your carefully crafted methods.

    So, amongst all the other reasons why you would use getters and setters you are also signalling your intent to others, and in doing so you are to some degree (some would say to a great degree) you are documenting what you have done.

    Hope this puts get/set into some context, but be aware that they should be used wisely are getters and setters evil?

  5. #5
    padawan silver trophybronze trophy markbrown4's Avatar
    Join Date
    Jul 2006
    Location
    Victoria, Australia
    Posts
    4,108
    Mentioned
    28 Post(s)
    Tagged
    2 Thread(s)
    the text book reasons for getters and setters is encapsulation, meaning that you can keep variables private from outside tampering so that they are never invalid.

    Unless you have a specific need for them don't, the less code the better.

  6. #6
    Non-Member
    Join Date
    Feb 2012
    Posts
    892
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Thewhistler_1 View Post
    It seems like it has the same result
    The difference between reading and inquiring properties.

    It's about the answers.
    The public properties will be easily read by everyone, no questions asked.
    The protected properties, everyone will have to inquire to get an answer.

    It's also about the questions.
    The question one is asking may not be so straightforward.
    The answer to that question could be a little more complex and it may not be held in one single property.

  7. #7
    SitePoint Wizard bronze trophy Jeff Mott's Avatar
    Join Date
    Jul 2009
    Posts
    1,264
    Mentioned
    18 Post(s)
    Tagged
    0 Thread(s)
    Part of the reason is data integrity -- a setter method can check values before allowing a property to be set. Part of the reason is complex setter behavior -- setting one property might include setting another property. For example, setCreatedOn might also call setExpiresOn. And another reason is future maintenance. When you first built your app, maybe you didn't have an expiresOn property, so you thought it would be safe to set the createdOn property directly. But as your app evolves, and now setting createdOn needs to do more work and therefore needs to be changed to a setter method, that means everywhere in your application where you accessed the property directly needs to be updated. It would have been a lot easier on yourself if you had just made it a setter in the first place.
    "First make it work. Then make it better."

  8. #8
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,810
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    Setters can include validation to ensure that the content is always valid when stored and that any other criteria for being allowed to update the value are also met.

    Getters can be use specific and provide the required escaping when required.

    Also it allows you to use any internal format you like - a simple example would be a date field where the internal value is often stored as a number and the getters and setters convert between that internal number format and the various formats that a date might be in.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •