Effective C # Principle 23: Avoid returning references to internal class objects

Source: Internet
Author: User

As you already know, the so-called read-only attribute means that the caller cannot modify this property. Unfortunately, this is not always valid. If you create an attribute that returns a reference type, the caller can access the public members of the object, as well as modify the state of those properties. For example:

public class MyBusinessObject
{
 // Read Only property providing access to a
 // private data member:
  private DataSet _ds;
 public DataSet Data
 {
   get
  {
   return _ds;
  }
 }
}
// Access the dataset:
DataSet ds = bizObj.Data;
// Not intended, but allowed:
ds.Tables.Clear( ); // Deletes all data tables.

Any mybusinessobject public client can modify your internal dateset. The attributes you create are used to hide the internal data structure of the class, and you provide a way for the client to know the method to manipulate the data skillfully. Therefore, your class can manage any changes in the internal state. However, read-only properties open a backdoor for the encapsulation of a class. When you consider these issues, it is not a readable writable property, but a read-only property.

Welcome to a wonderful reference based system, any member that returns a reference returns a handle to the object. You give the caller a handle to an interface, so the caller no longer needs to pass this object when modifying an internal reference to the object.

It is clear that you want to prevent such a thing from happening. You create an interface for your class, and you want the user to use this interface. You do not want users to access and modify the internal state of an object when they do not understand your intent. You have four strategies to protect your internal data structures from unintentional modifications: value types, constant types, interfaces, and wrappers (patterns).

A value type is a copy of the data when it is accessed through a property. Any changes that the customer makes to the copy data of the class do not affect the internal state of the object. The customer can modify the copied data randomly according to the requirement. This has no arbitrary effect on your internal state.

Constant types, such as System.String, are also safe. You can return a string, or other constant type. Constant type of security tells you that no customer can modify the string. Your internal state is safe.

The third option is to define the interface so that customers can access some of the functionality of the internal members (see Principle 19). When you create a class of your own, you can create a set of interfaces that support the setting of the child objects of the class. By exposing some function functions through these interfaces, you can minimize some unintended changes to the data as much as possible. The client can access the internal object of the class through the interface you provide, and this interface does not contain all the functionality of the class. Exposing a IListSource interface on a dataset is the tactic that prevents some thoughtful programmers from guessing about the objects that implement this interface, as well as the casts. Doing this and programmers doing more work and finding more bugs is self-inflicted (this may be completely wrong, and readers can refer to the original text: But programmers who goes to so much work to create bugs get what They deserve.).

The System.dataset class also uses the last policy: wrapping objects. The DataViewManager class provides a way to access the dataset, and prevents the method of transformation from accessing the Dataseto class:

public class MyBusinessObject
{
 // Read Only property providing access to a
 // private data member:
 private DataSet _ds;
 public DataView this[ string tableName ]
 {
  get
  {
   return _ds.DefaultViewManager.
    CreateDataView( _ds.Tables[ tableName ] );
  }
 }
}
// Access the dataset:
DataView list = bizObj[ "customers" ];
foreach ( DataRowView r in list )
 Console.WriteLine( r[ "name" ] );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.