Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class attribute declaration: private vs public

What are the advantages of defining a private attribute instead of a public attribute? Why should I have the extra work of creating methods to access and modify privates attributes if I can just make them public?

like image 563
brsunli Avatar asked Apr 03 '09 00:04

brsunli


People also ask

What is the difference between a private and a public attribute?

A private attribute provides you a level of protection from the users of your class, for that attribute. If you use a public attribute, you will need to add in more logic to test for invalid values up front, which can be more work, as well as more computationally expensive.

What does it mean if a class attribute is private?

Private. In the context of class, private means the attributes are only available for the members of the class not for the outside of the class.

Why are attributes declared as private?

In many object-oriented languages, certain attributes can be declared as private, making it impossible for users of a class to directly view or modify their values. The designer of the class then provides methods to control the ways in which these attributes can be manipulated.

What is the purpose of the keywords public and private in the class declaration?

Public, private and protected keywords are used to specify access to these members(properties and methods) of a class from other classes or other . dlls or even other applications.


2 Answers

In the short term there's none, other than making OOP purists unhappy.

(I'm assuming you mean exposing properties that would otherwise use getters/setters - obviously there's a big difference if you leave ALL your attributes public).

In the long-term there are a few really good reasons for doing it.

Firstly it allows you to validate input at its source instead of later having to back-track the origin with a combination of hardware breakpoints and black-magic.

E.g.

void Foo::setWeight(float weight)
{
  ASSERTMSG(weight >= 0.0f && weight <= 1.0f, "Weights must fall in [0..1]");
  mWeight = weight;
}

It also allows you to later change the behavior of your object without needing to refactor client code.

E.g.

void Foo::setSomething(float thing)
{
  mThing = thing;
  // 2009/4/2: turns out we need to recalc a few things when this changes..
  ...
}
like image 77
Andrew Grant Avatar answered Oct 26 '22 23:10

Andrew Grant


If you use getters/setters you can perform logic upon changes or access. You could validate input, instead of assuming it is always correct. You could track how many times the value is fetched.

Most of all, it's good design. It gives you, the developer of the class, more control over how it is used and a greater ability to prevent misuse, abuse, or just someone doing something wrong.

like image 43
Kalium Avatar answered Oct 27 '22 01:10

Kalium