Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best to use Private methods or Protected methods?

Tags:

oop

php

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?

like image 745
Ciaran McNulty Avatar asked Jan 07 '09 10:01

Ciaran McNulty


People also ask

When would you use protected methods vs private methods?

Protected methods are a balance between public and private methods. They are similar to private methods in that they cannot be accessed in the public scope. Neither the client nor the program can invoke them. However, objects of the same class can access each other's protected methods.

Is protected better than private?

Only the member functions or the friend functions are allowed to access the private data members of a class. The class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class. Private member are not inherited in class.

Should my method be public or private?

Generally you should expose as little as possible and make everything private that is possible. If you make a mistake and hide something you should be exposing, no problem, just make it public.

Should I use private methods?

Private methods are useful for breaking tasks up into smaller parts, or for preventing duplication of code which is needed often by other methods in a class, but should not be called outside of that class.


1 Answers

My instinct is to keep them private, until you need them to be otherwise.

It has been argued (sadly I've misplaced the link) that making methods private is antisocial, in much the same way as making them 'final', in that it's fairly dictatorial about how people may use your code.

I'm not convinced, however, and agree that you should expose only what you really need to. The exception would be a library or toolkit, where you'll expect users to want to extend (in the general sense) your code in ways which you would never foresee. In which case making well-chosen methods protected can be seen as providing flex-points.

like image 189
12345 Avatar answered Oct 09 '22 04:10

12345