1) One reason to use encapsulation is that by hidding internal implementation details we are able to modify this details without breaking the existing code – this makes perfect sense
a) But I don’t understand the argument that encapsulation should be used in order to prevent users from setting the internal data of an object into an invalid or incosistent state.
If I write a class and sell it to other programmers ( who implement this class into their own applications ), then shouldn’t they be responsible to access this object in a correct way? After all, if they don’t use the object correctly then it will only be their applications that will suffer because of it.
An analogy ( a bad one ) of me having to implement encapsulation for the sake of other programmers not putting internal data ( either accidentally or on purpose )into incosistent state, would be selling water proof TVs just in case buyers decide to swim with their TV sets.
2) From
void Foo(Giraffe g) {} void Bar(Animal a) {} Action<Mammal> action1 = Foo; // illegal Action<Mammal> action2 = Bar; // legalWhy is the first assignment illegal?
Because the caller of action1 can pass
a Tiger, but Foo cannot take a Tiger,
only a Giraffe! The second assignment
is legal because Bar can take any
Animal.«
I understand author’s reasoning on why Action<Mammal> action1 shouldn’t be able to accept Foo(). But on the other hand, shouldn’t it be the programmer’s responsibility to not pass into delegate any arguments that registered methods can’t handle?
Thus, if some programer registers method Foo, then they will also know :
• not to call action1 delegate with anything else than with Giraffe argument
• Not to register methods with different signature than Foo ( except if method defines as its parameter a type from which Mammal derives )
thanx
One of the advantages of good encapsulation is to “force” the user of the class to use it in the proper way, and not in any other possible way. This way, the user is less frustrated about the code he has to (re)use. The productivity increases (less time spent figuring out why the code breaks, especially if the source code is not available), etc.
If I have to buy a library from someone, and I have to be very careful on how I have to use it at each step, I would consider that I wasted money.
(I excluded the library design topics, stability, maintainability and extensibility. I am mortal, and the time to cover these aspects is limited :)…)