I'm creating interfaces for a number of our existing classes for mocking reasons. Many of these classes also have package scope methods as an attempt to give some level of encapsulation by ensuring only the controller can modify some of their state. I had thought I could use this change to try to get cleaner encapsulation as well.
My question is two fold. First, is it considered viable to use interfaces for encapsulation? I could make certain methods not in my interface that are available in the class. or I could have my IBar method have a getFoo method that returns an IFoo, but my bar class overrides getFoo to return a Bar. The problem is that anyone could easily cast my Ixxx to the actual class, so is it really considered a worthwhile encapsulation?
My second question has to do with my model. I would want my model to have some getAllFoo sort of methods that return IFoo objects. however, I want my controller to have a way to fetch the actuall Foo implementation (ie, know that my IFoo is of type Foo) so that it has access to methods not in the interface. What is considered the cleanest way to ensure my controller has access to the full class but other classes only see the interface? I asume just casting the interface to it's concrete class would be considered rather sloppy?
Best Answer
Whenever casting is a problem for encapsulation depends whenever you have Enabling or Directing attitude. For person with directing attitude, the fact that you can upcast to bypass the encapsulation is definitely a problem, so they probably won't see using an interface as proper encapsulation. But for person with enabling attitude, this is not a problem, because for them it is enough that interface tells programmer what methods are safe to use and that any programmer will be well aware of problems and risks that upcasting can bring and will not use it lightly.
There is also case of using public interface with private or internal class. Then the problem of upcasting goes away, because compiler won't allow access to the private class so you could upcast.
And lets not forget about reflection. Even if programmer is limited by encapsulation, reflection can usually get around it. So there is always a way to break encapsulation if programmer thinks it will solve his problems.
As for your model question. Where is the problem of keeping
collection of Foo
internally in controller but returningcollection of IFoo
to the outside world?