views:

34

answers:

2
interface IFoo
{
    int MyReadOnlyVar { get; }
}


class Foo : IFoo
{
    int MyReadOnlyVar { get; set; }
}


public IFoo GetFoo()
{
    return new Foo { MyReadOnlyVar = 1 };
}

Is the above an acceptable way of implementing a readonly/immutable object? The immutability of IFoo can be broken with a temporary cast to Foo.

In general (non-critical) cases, is hiding functionality through interfaces a common pattern? Or is it considered lazy coding? Or even an anti-pattern?

A: 

You may make Foo class visible at assembly level only (internal in C#), or make setter of MyReadonlyVar internal, so your code will be protected from unnecessary casts outside of assembly.

STO
+1  A: 

Using interfaces to hide make the interface of a class smaller is a proper usage. I have seen lot's of such code in Spring applications where the dependencies are only expressed in the class (and used by Spring dependency injection) and not in the interface because they do not provide anything for the domain.

You can't protect your code from other coders. If you are afraid someone would cast the interface to the mutable version the same could happen if you return a real read only snapshot and someone on your team adds mutating methods to it.

It also depends on your code. Inside a project/application you might trust your collegues. When developing a framework things are different. Then you have to decide if to alyways return "save" objects, e.g. clones of lists instead of the real lists that might be modified.

So yes, in general (non-critical) cases IMHO it's proper to do it your way.

Peter Kofler