Permission to change parameter and return references

When you hold a reference to an object you can change its state by for example calling methods of the object which have side effects or by setting different values for fields or properties. On first sight this is very natural to OO programming but can lead to problems when others do the same with the same object. Imaging you pass a collection to a method as parameter and while the method enqueues the collection for further processing, you keep on changing it. This can lead to behavior you most likely did not intend: You wanted the method to work with the state of the collection it had when you called the method. Instead it will use the state it has at the time of processing. Ideally all parameters your method takes are immutable (like primitive / value types or string) but in reality this will not always be possible.

Do provide clear documentation for a method regarding who has permission to change the content of all referenced objects reachable by reference type parameters after the method returns.

Similar to the (in) parameters the same thoughts apply for the (out) return value.

Do provide clear documentation for a method regarding who has permission to change the content of all referenced objects reachable by the returned value.

Following example illustrates documenting parameters

/// <summary>
/// Creates new customers in database
/// </summary>
/// <param name="customers">List of new customers</param>
/// <remarks>All reference type parameters and their children
/// must not be modified after calling this method.</remarks>
public void CreateCustomersInDatabase(List<customer> customers)
{
// ..
}

In this example it becomes clear why it is important to clarify that none of the reachable objects from any reference type parameter must be changed. Even though the caller might not modify the List he still might change the state of Customer objects referenced by the List. Obviously that is also not wanted by the method.

 

Do always prefer using immutable data structures.

 

Flattr this!

Leave a Reply

Your email address will not be published. Required fields are marked *