Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
May 5, 1998

Why you should avoid direct access to data members

Sometimes it may be tempting to declare class data members as public. However, this is not recommended for the following reasons:

1. Users of such class rely heavily on its implementation details, and when the class needs to be extended or changed, it can become a maintenance nightmare to them, since they have to track each and every piece of code related to that class. Infra-structure components, such as Date or String classes, can be used dozens of times within a single source file. You can imagine what it's like when dozens of programmers, each producing dozens of source files have to chase every source line using these classes in their programs. This problem is exactly what caused the notorious Year 2000 Bug! If, on the other hand, the data members are declared as protected or private, users cannot access the object's data directly and have to use accessors and mutators (also known as "Getters" and "Setters," respectively) for that goal. When the implementation details of the class are changed, only accessors and mutators need to be modified, and not any other pieces of code.

2. Users can inadvertently tamper with the object's internal data members. For example, they can delete memory which is supposed to be deleted by the destructor; change the value of a file handle, let the destructor close the wrong file, and so on. The results of such tampering may cause an undefined behavior, and hence unreliable software components and bugs that are very hard to detect.

So it's always a better design choice to hide implementation details by prohibiting public access to an object's data and using accessors and mutators instead.

Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date