I'm using "protected" instead of "private", because someday I could need to extend my classes, is that bad?

313 views Asked by At

I have noticed a pattern in my code. I usually choose protected, rather than private, as default access label for "hidden" methods and fields in my classes. I mainly do this because it hides the details about the class functioning for users of the class, while still leaving space for extension in the future. Is there any drawback in this coding "policy"?

Thank you
Tunnuz

3

There are 3 answers

1
Mark On BEST ANSWER

Generally speaking never make something because some day you might be having to implement or do yadayada (it just makes life complicated and miserable Imho..). If you have a method that should only be used within its class, then make it private. If you ever have to extend it by inheritance than reconsider which functions might have to accessed from bellow. Usually I anyway abstract methods to my superclass so then I anyway have to do the thinking of what will be needed when and where..

A good reason why to ignore what I said about private methods, is if you want to test your internal functions i.e. in a unit test. In C# you can allow another project to see your protected methods from externally so you can write tests against them.

0
oopbase On

I don't think there's a drawback.

  • Private variables, are variables that are visible only to the class to which they belong.
  • Protected variables, are variables that are visible only to the class to which they belong, and any subclasses.

So everything should be ok with your code. There's nothing "bad" about that. If you probably extend your class, the protected property will be definately right.

0
Gursel Koca On

You should choose private , because of encapsulation. I do prefer conservative approach on this subject, I prefer private access modifier, if I do expect some extension then I choose protected access modifier. It is not good practice to choose protected modifier instead of private.