views:

1341

answers:

4

What I need is to make sure that in most scenarios objects are used via "readonly interface", which is a subset of the full interface.

  • If I were in C++, I would just return a const object, for instance.
  • If I could use interfaces, I would just implement a readonly interface and use it everywhere, however, I need operator overloading, which is not allowed for interfaces, that's why I have to use abstract base class.
  • But if I define abstract base class, I am not allowed to change accessibility in the derived type..

Any ideas? Thanx

A: 

You could implement the readonly behaviour via state in the object, and throw an exception if a modifying method is called?

frankodwyer
+2  A: 

How about if you placed your write operations in an interface and then implement in explicitly on the abstract base class? It would not be a 100% perfect solution (you could still cast the object to the modification interface), but for most part it would prevent anyone from accidentally calling the modifying methods.

Vilx-
@Vilx - I like your suggestion, though, I decided not go go for it, because J. Richter suggests to avoid explicit interface implementation as much as possible...in particular, because I will do a lot of these casts, even if I am in derived type.
badbadboy
Why not make an interface that contains both read and write methods? Implement the read methods implicitly, and write methods explicitly. Then you will just have to cast it once to get a read-write object.
Vilx-
+2  A: 

Do you really NEED operator overloading? We are talking about syntax sugar here. Plus, not all languages utilize operator overloading the same. If you use it you are effectively making your code language specific.

I would implement the readonly interface and drop the operator overloading requirement.

Chris Brandsma
@Chris - in a different application I would totally agree :) I've almost done it. In this one (computational) - it is very unfortunate to drop it, it is actually more unfortunate than dropping readonly requirement...
badbadboy
ReadOnly, or const, for a parameter constraint is something I would like to see in C# as well. Creating read-only interfaces is not the greatest solution.But sometimes you just have to live in the language you are using.
Chris Brandsma
A: 

If anyone is interested in what I did, I finally went for an abstract class instead of interface, and I did hide the method in the derived class to get the right accessors:

Like, in the base abstract class (readonly interface):

protected double accuracy;
public double Accuracy { get { return accuracy; } }

In the derived class:

public new double Accuracy
{
    get { return accuracy; }
    set { accuracy = value; }
}

Of course, ugly with the "new" keyword, but in this case it will do for me.

badbadboy