Protected Methods and Properties is a Bad Idea

Igor Vorobiov
2 min readFeb 16, 2018

--

I often see programmers prefer to not define “private” members of a class at all. Instead, they define only “protected” members explaining it by the fact that they don’t know whether this method or that property is going to be used or not in child classes. Therefore, to be safe in advance and to minimize work effort needed in the future, they think that it’s better to have all the members of the class “protected”.

Well, that’s a clever move, but programming languages allow to have “private” members for a reason.

First of all, having only “protected” members in a class breaks encapsulation from the perspectives of a parent class. It allows users to change the state and the behavior inherited from the parent class even thought the author of the parent class didn’t plan that.

Obviously, this goes against the principles of OOP and can cause problems easily. For the same reason, we can just make all the members of the class “public” and pray that users won’t mess up the internal logic of an instance.

Bear in mind, the more things you keep in private, the less things you have to protect, the more stable code you will get.

Next, if a class has more “private” and less “protected” members your confidence in doing refactoring of that class will be significantly increased.

When you want to change the logic or rename one of the “private” methods of the class you are 100% sure that this method is only used within that class. Therefore, it requires less efforts, less attention and gives more confidence to accomplish that. On the contrary, when you see all the methods within the class are “protected” you prefer to not touch them at all because you have no idea where else they are used in the project. You are not sure which child classes refer to those methods, and as a consequence, changes in them might be simply too stressful and dangerous.

Summary

Hopefully, I have convinced some of the programers to give a preference to “private” members and think twice before defining “protected” members.

In some sort, “protected” and “public” members are the same in their nature. The only difference is their level of access.

--

--