views:

176

answers:

1
interface IDependency
{
    string Baz { get; set; }
}

class Foo
{
    IDependency dependency;

    public Foo(IDependency dependency)
    {
        this.dependency = dependency;
    }

    public void FubarBaz()
    {
        dependency.Baz = "fubar";
    }
}

I could also implement this as:

class FooStatic
{
    public static void FubarBaz(IDependency dependency)
    {
        dependency.Baz = "fubar";
    }
}

When should I choose immutable objects over static methods? Are there any situations where the reverse might be true?

Also, it seems to me that immutable objects should not have void methods. What do you think?

+3  A: 

Immutable objects can certainly have void methods - there are other kinds of side-effects beyond changing the state of an object. Consider:

public void WriteTo(Stream stream)

as an example.

As for your "immutable objects vs static methods" issue - what if your method actually needs a few aspects of the state of Foo? Just because the state doesn't change doesn't mean that it doesn't make sense to encapsulate that state together. Suppose it has 5 dependencies instead of one - do you want to write lots of static methods that take 5 parameters? When you gain a sixth dependency (or even just another piece of state) do you really want to have to add the sixth parameter to all the methods, or just to the constructor?

Jon Skeet
Thanks for the reply; declaring dependencies the ctor seems reasonable enough to me. In response to your first paragraph, though, doesn't WriteTo modify the state of stream?
Sam Pearson
@Sam: Yes, it modifies the state of the stream - but not the state of the object you call it on. The stream is mutable, but the object could be immutable... so it's still a void method on an immutable object, without being pointless.
Jon Skeet