Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should disposable objects be passed in?

Tags:

c#

In a code review a co-worker changed my code to pass in a Stream as a parameter. He said this was to ensure that the responsibility to dispose of the object is clear to the caller. In a sense I can empathize. I would prefer the object creator to also be responsible for cleanup.

On the other other hand, neither method makes the need for a using any more clear. I prefer the simpler method call as well.

Take

    public static TextReader Serialize<T>(T obj) where T: new()
    {
        if (obj == null) throw new ArgumentNullException("obj");
        return Serialize<T>(obj, null);
    }

VS

    public static void Serialize<T>(T obj, TextWriter outbound) where T : new()
    {
        if (obj == null) throw new ArgumentNullException("obj");
        Serialize<T>(obj, outbound, null);
    }

Is there any technical reason to add the extra param?

like image 954
P.Brian.Mackey Avatar asked May 14 '12 19:05

P.Brian.Mackey


1 Answers

It strictly depends on your code architecture.

I, personally, like the second approach (even if it adds one more argument) where definition of the function states that it will not close/dispose a stream, but it's up to the Caller.

This is very useful in case when you're going to call the same functions on the same stream, cause if you imagine, that every function call will close and reopen the stream, it becomes resource consuming operation.

like image 68
Tigran Avatar answered Sep 28 '22 23:09

Tigran