Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API design dilemma about clean up responsibility

Tags:

c#

Suppose you have a library that provides a method that accepts an object that needs to be cleaned up. E.g. by calling its Close or Dispose method. Who should be responsible? The caller or callee? Ofcourse you can choose either way as long as you document this properly. But is there consensus or best practice about this?

Here is an example:

// public method of library
public class MyObject
{
   public void Read(System.IO.Stream stream)
   {
      ...
   }
   ...
}

If the caller would be responsible, the client code should look like this:

using (FileStream file = new FileStream(...))
{
   MyObject myObject = new MyObject();
   myObject.Read(file);
}
like image 478
Frank Avatar asked Jan 23 '26 07:01

Frank


2 Answers

I would say the normal "ownership" is for whoever creates the resource to start with - so the caller of your method. Aside from anything else, who's to say that the caller wants to dispose of the stream after reading? Perhaps they want to rewind it and pass it to something else.

I generally get nervous of disposing of anything I haven't explicitly created. There are exceptions to this of course - the Bitmap(Stream) constructor effectively takes ownership of the stream, and assumes that you'll dispose of the bitmap which will in turn dispose of the stream... but I'd say that's the exception rather than the rule.

like image 186
Jon Skeet Avatar answered Jan 24 '26 19:01

Jon Skeet


In general, the caller should clean up, since you don't know whether the caller is really done with his object.

However, if your method "consumes" the object such that the caller can't use it again (eg, if it reads up a non-seekable stream), then you might want to dispose it yourself.

like image 45
SLaks Avatar answered Jan 24 '26 21:01

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!