4

After learning about encapsulation in OOP, I started to use only protected and private properties, share data via accessors and change properties via mutators.

Right now, I'm afraid of declaring public properties.

Is it good to keep everything private and protected or is there some cases where I need to use public properties?

3

If you don't need control over a data/property you are exposing, you can use public property with no problem.

For all other cases (like if it's a property with only in-class use or if you want to expose a property on which you want to keep read/write control), it's better to keep them private and some time protected if you plan for your class to be inherited

  • Good answer! What about chaining in some language? I saw some code where properies exposed to gain chaining without fluent interface. It is just bad planned architecture? – volter9 Dec 23 '14 at 1:11
  • 1
    It also depends on the language. In C# or Python you can always go back and make the field a property if you need extra behavior; in Java not so much; the future-change risk of exposed fields is much higher in java. – StarWeaver Dec 23 '14 at 3:10
  • Let's say JS or PHP, what about them? – volter9 Dec 23 '14 at 4:57
  • How come everywhere I got to work, It's considered super-bad practice to have any public property and instead have properties private or protected and have getters and setter that do nothing else but get and set ? – Ki Jéy Jan 31 at 1:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.