If I’m writing a class, when do I make a method private, versus protected? In other words, how I can know in advance that a client programmer would never ever need to override a method? In a case where it’s something that has external considerations, like a database connection?
Share
publicandprotectedmethods form the ‘interface’ to your object,publicfor developers using (delegating to) your class, andprotectedfor developers wishing to extend the functionality of your object by subclassing it.Note that it’s not necessary to provide
protectedmethods, even if your class will be subclassed.Both
publicandprotectedinterfaces need careful thought, especially if this is an API to be used by developers outside your control, since changes to the interface can break programs that make assumptions about how the existing interface works.privatemethods are purely for the the author of the object, and may be refactored, changed and deleted at will.I would go for
privateby default, and if you find you need to expose more methods, have a careful think about how they will be used – especially if they are virtual–what happens if they are replaced completely with an arbitrary alternative function by another developer–will your class still work? Then design some appropriateprotectedwhich are useful for developers subclassing your object (if necessary), rather than exposing existing functions.