devxlogo

Read-only members

Read-only members

Question:
If I write a class in C++, which contains private members, I can make them read-only by providing a get access method and no set access method. If that member is large and I want to return it by reference, I can maintain security by returninga const reference. Without being able to do this, what does a Java programmer do to make read-only member objects, accessed (as they must be) by reference?

Answer:
Const references in C++ can be compromised by casting and throwing away the const attribute. So the problem you are trying to solve for Java also needs to be solved for C++. A solution that will work in both languages is to tackle the problem through design rather than language features. Think carefully about why you want to grant access to a private member variable. If you are designing a class library and other classes need to read the value of the variable, then it isbetter to make the variable package local if you are concerned about providing efficient access to the value. Within the package, you can enforce read-only access by ensuring that all external class accesses within the package do not modify the value of the variable. The safest solution is probably not to return a reference to the variable in a get method in either Java or C++. Rather, you should copy the value of the variable to a new variable. A shallow copy may be sufficient for some data structures, but remember to make deep copies when necessary. Finally, if the variable is truly to be read-only in all situations, it should be declared final and initialized a single time.

See also  How to Avoid Money Transfer Scams  
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