Alex Rivera | Logout

Best to use Private methods or Protected methods?

Asked 2009-01-07T10:35:13.747
37

In a lot of my PHP projects, I end up with classes that have non-public functions that I don't intend to extend.

Is it best to declare these as protected, or private?

I can see arguments both ways - making them private is a far more conservative approach, but it can be argued that they could be made protected later if I want the method to be extended and it makes it clear which methods are extended by base classes.

On the other hand, is using private somehow antisocial, in that it impedes a theoretical future developer from extending my code without modification?

Edit
Report

1 Answer

1

As said, if you are going to extend a class later you can always change it then.

But if you can avoid to use inheritance you should. It is better to use other patterns when designing, if possible.

Basically what to do is favor composition over inheritance and program to interfaces, not to implementations.

If you let classes just have one tightly defined purpose than you can composit objects instead of letting them inherit each other. If you use interfaces rather then inheritance you will most likely define small and effective interfaces. Then you will see that inheritance will reduce and therefore the need for "protected" will reduce too.

Example

interface sound {
 public function makeSound();
}

class bark implements sound{
 public function makeSound() {
   return "Bark!!!";  
 }
}

class meow implements sound{
 public function makeSound() {
   return "Meowmeow!!!";  
 }
}

class fourLeggedAnimal {
  private $sound;

  public function fourLeggedAnimal($sound){
    $this->sound = $sound;
  }
 
  public function eat(){
    echo $this->sound->makeSound();
  }

}

$cat = new fourLeggedAnimal(new meow());
$dog = new fourLeggedAnimal(new bark());

I know this far from a perfect example. But it illustrates the technique and you can use this in many ways. For instance you can combine this with different creational patterns to build cats and dogs, it may not be so wise to have to know if a cat barks or meows.. But anyway.. it differs from having to make a base class and then extending it with a cat and a dog, and therefore have to make the "sound" method protected or overriding the public eat method.

/Peter

answered 2009-07-26T11:08:52.143

Your Answer