devxlogo

Why you should avoid direct access to data members

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.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist