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; // legal
Why 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