开发者

Method hiding with interfaces

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 immutabi开发者_如何学编程lity 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜