Page 1 of 1

Use a protected function or wrapper method?

Posted: Tue Oct 23, 2012 5:57 pm
by social_experiment
Assume my class has the following 3 methods inside it

Code: Select all

<?php
class SomeClass 
{
 /**
   *
   */
 protected function _retrieveName()
 {
     // code
     return $name;
 }

 /**
   *
   */
  protected function _displayName()
  {
      // I need the name, which function do i use to get it?
  }

 /**
   * Wrapper function
   */
 public function getName()
 {
     return $this->_retrieveName();
 }
}
?>
_retrieveName() is a protected method, getName() acts as a wrapper function for the protected method. As per my example, if i need to get the name and i want to use an existing function, which one of the two would i use? My initial thought would be to use the protected method directly in the class wherever i need its functionality and the public function would be used outside the class

Re: Use a protected function or wrapper method?

Posted: Tue Oct 23, 2012 7:12 pm
by requinix
If all getName() does is call a protected method then I wouldn't bother with the protected method at all. It's just (a tiny bit) extra overhead for absolutely no gain. You don't have to create some artificial barrier between public methods and protected methods: let the functionality and requirements dictate where code is and how visible it needs to be.

For the general case, what do I do... In the general case all the methods have different, even if slightly, behavior. There shouldn't even be a choice to make in the first place. And I say that as the conceptual "I think that's how my code works" answer - I don't think I've ever had this problem before.

Re: Use a protected function or wrapper method?

Posted: Tue Oct 23, 2012 9:48 pm
by Christopher
The only reason I can think of to call one or the other is that calling getName() has the overhead of an extra function call. My concern with this interface is that whichever you pick, it is possible in the future that some code will get added to getName(). That will make the two methods different. Then there is a 50/50 chance that internal calls to one or the other may be to the wrong method.

Re: Use a protected function or wrapper method?

Posted: Wed Oct 24, 2012 2:07 am
by social_experiment
Thank you both for your replies;
requinix wrote:I don't think I've ever had this problem before.
I've actually be using this approach for a while because i thought that using a wrapper method was a better alternative than to using a function 'directly';
Christopher wrote: My concern with this interface is that whichever you pick, it is possible in the future that some code will get added to getName().
Ah yes i hadn't taken this into account because most of the time the protected method would have a specific purpose and rarely would that purpose change but it is definitely something i'll take into account in future projects