473,770 Members | 2,719 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Read-only properties returning reference types

I am not sure what the suggested practice is for returning reference types
from read-only properties. Consider an example: Suppose I have a Point
class that is a reference type. I use the Point class from within a Shape
class. I want the user of the Shape class to be able to see the location of
the Shape but not be able to change it. So I declare a read-only property:

class Shape {
private Point location;
/* other Shape stuff */

Point Location
{
get
{
return location;
}
}

/* ... */
}

However this has a problem. The get accessor returns a reference type, so
whoever accesses the property can use that reference type to modify the
private member variable:

Shape shape = new shape(...);
Point point = shape.Location;

// Modify internal member variable through returned reference!
point.x = newxvalue;

What are the recommended ways to circumvent this problem? I see two
solutions: 1) return a copy of the location Point class or 2) make each
field of location, x and y (and z?), a read-only property of Shape that
returns a value type. I think solution 2) could get out of hand with too
many properties being required. I am not sure if 1) is recommended or not.
All the examples I can find of creating read-only properties use only value
types so they do not answer my question.
Nov 15 '05 #1
2 2101
I think the way I would address this is to have the members of your Point
object be readonly, plus add some internal properties that offer write
access. This way they can be read and altered by Shape, but only read by
any client using the object.

"Cory Burkhardt" <bu********@hot mail.com.nospam > wrote in message
news:40******** *************** @news.twtelecom .net...
I am not sure what the suggested practice is for returning reference types
from read-only properties. Consider an example: Suppose I have a Point
class that is a reference type. I use the Point class from within a Shape
class. I want the user of the Shape class to be able to see the location of the Shape but not be able to change it. So I declare a read-only property:
class Shape {
private Point location;
/* other Shape stuff */

Point Location
{
get
{
return location;
}
}

/* ... */
}

However this has a problem. The get accessor returns a reference type, so
whoever accesses the property can use that reference type to modify the
private member variable:

Shape shape = new shape(...);
Point point = shape.Location;

// Modify internal member variable through returned reference!
point.x = newxvalue;

What are the recommended ways to circumvent this problem? I see two
solutions: 1) return a copy of the location Point class or 2) make each
field of location, x and y (and z?), a read-only property of Shape that
returns a value type. I think solution 2) could get out of hand with too
many properties being required. I am not sure if 1) is recommended or not. All the examples I can find of creating read-only properties use only value types so they do not answer my question.

Nov 15 '05 #2
Cory Burkhardt <bu********@hot mail.com.nospam > wrote:

<snip>
What are the recommended ways to circumvent this problem? I see two
solutions: 1) return a copy of the location Point class or 2) make each
field of location, x and y (and z?), a read-only property of Shape that
returns a value type. I think solution 2) could get out of hand with too
many properties being required. I am not sure if 1) is recommended or not.
All the examples I can find of creating read-only properties use only value
types so they do not answer my question.


2) is recommended *anyway* - you shouldn't (IMO) have any non-private
fields, in general.

Immutable objects are generally a good thing when they can fit into
your design easily - they make situations like this much simpler. If
the object is mutable, then you have to make a copy to be safe -
although within internal implementations , I usually find that
documenting what should and shouldn't be changed by the calling code to
be sufficient.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3477
by: Steve | last post by:
Hi, I'm trying to convert a file reading loop into one using streams. The BSD OS read API returns the number of bytes read, but istream::read returns itself. How can I find out the number of bytes actually read? What the code fragment should do is read up to 1000 bytes into a buffer, or finish early if reading failed. Just your average read loop. I have: (this is a simplified version; I know there's no detailed error
0
1879
by: munif | last post by:
i wnat write a C++ program that would read from a CD and display information about files and folders in the given CD In simple words you would be performing a simple (ls -l) or (DIR /S) on the CD. LOOk at this code /*
12
11666
by: Steven T. Hatton | last post by:
I know of a least one person who believes std::ifstream::read() and std::ofstream::write() are "mistakes". They seem to do the job I want done. What's wrong with them. This is the code I currently have as a test for using std::ifstream::read(). Is there anything wrong with the way I'm getting the file? #include <vector> #include <iomanip> #include <fstream> #include <iostream>
2
3092
by: Sandman | last post by:
Just looking for suggestion on how to do this in my Web application. The goal is to keep track of what a user has and hasn't read and present him or her with new material I am currently doing this by aggregating new content from all databases into a single indexed database and then saving a timestamp in the account database (for the current user) that tells me when the user last read items in the aggregated database.
2
2509
by: Andrea Bauer | last post by:
Hallo, wie kann ich so eine Datei unter .Net schreiben C++ oder C#. Bitte mit Funktionsaufrufen. Vielen Dank. Grüße Andrea <Product> <ProgramNumber>2</ProgramNumber>
4
3847
by: Ollie Cook | last post by:
Hi, I am having some difficulty with read(2) and interrupting signals. I expect I am misunderstanding how the two work together, so would appreciate some guidance. I am trying to 'time out' a socket read after a certain delay. The logic is (I will provide a test program below): - create and connect socket
1
5787
by: Arpan | last post by:
The contents of a text file are as follows: The Quick Brown Fox Jumped Over The Lazy Dog. Note that there isn't any space at the end of each of the 3 lines. Now when I do this:
6
5716
by: arnuld | last post by:
This works fine, I welcome any views/advices/coding-practices :) /* C++ Primer - 4/e * * Exercise 8.9 * STATEMENT: * write a program to store each line from a file into a * vector<string>. Now, use istringstream to read read each line * from the vector a word at a time.
4
2804
by: zl2k | last post by:
hi, there I have a appendable binary file of complex data structure named data.bin created by myself. It is written in the following format: number of Data, Data array Suppose I have following data.bin (3 Data appended to 2 Data): 2, data0, data1, 3, data0, data1, data2
5
12869
by: Thomas Christensen | last post by:
This issue has been raised a couple of times I am sure. But I have yet to find a satisfying answer. I am reading from a subprocess and this subprocess sometimes hang, in which case a call to read() call will block indefinite, keeping me from killing it. The folloing sample code illustrates the problem: proc = subprocess.Popen(,
0
9453
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10254
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10036
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9904
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5481
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3607
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2849
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.