tags:

views:

41

answers:

3

I'm writing a class that has two objects as private members, one of which is conceptually referenced by the class, and the other is conceptually owned by the class. However, the code itself gives no clue that this is the case.

public class WorklistSearchResults
{
        //This is "owned" and will be disposed
        private RecordSet _RecordSet = null;
        private RecordSet RecordSet
        {
            //...
        }

        //This is "referenced" and won't be dispoesd
        private WorkList _WorkList = null;
        private WorkList WorkList
        {
            //...
        }
        //...   
}

Is there a standard way to differentiate between the owned and referenced object? Are comments the only way to go here?

+1  A: 

In languages such as C++, you may embed the owned object into the class, and point at the referenced object via a pointer.

In languages such as Java or C#, however, that solution is not usually available. As far as I know, most modern OO programming languages do not differentiate between owned and referenced objects; this is a difference that makes a lot of sense at the conceptual modelling level, but for some reason programming languages choose to ignore it.

Personally, I rely on comments and patterns to implement the differences.

CesarGon
Do you have a suggestion for a pattern?
C. Ross
Yes. A pattern I used for a C# system a while ago was that all "owned" objects implemented IDisposable, and Dispose() was called from the owner class as appropriate. This "chained disposal" is analogous to the cascading destruction of embedded objects in C++, for example.
CesarGon
@CesarGon That's funny, b/c what I was trying to find was a way to illustrate that these objects should be disposed and these others shouldn't.
C. Ross
+1  A: 

What does "dispose" mean? In some languages you would write

 myTidyUp() {

      delete _RecordSet;
      _RecordSet = null;

      // not owened so don't delete
      _WorkList = null;

 }

But in a garbage collected language we just code:

 myTidyUp() {      
      _RecordSet = null;
      _WorkList = null;
 }

No difference, the owned or not distinction is in the _RecordSet's lifecyle/factory/registry code.

If there is some kind of open/close life cycle requriements (like we have on JDBC connections) then that protocol is defined by the dependent object.

My tentative conclusion: in a garbage collected environemnt the docuemnted life-cycle of the "owned" objects gives us our distinction. In a non-GC environmemnt we manage the tidy up using smart pointers where needed. The use of smart pointers makes the ownership clear.

djna
This is more like the life cycle on a JDBC connection. In java the call would be `close()`, in C# it's `.Dispose()`.
C. Ross
A: 
Owen S.
An interesting concept. I'll have to think about it.
C. Ross