> From: Anton Tagunov [mailto:[EMAIL PROTECTED]
>
> Still not completely convinced.
> Please refer to the examples in the letter to
> Niclas, don't they protect the opposite opinion?
I don't think so. Your example is this:
Context ctx = makeNewContextSomehow ();
... do stuff to context ...
if (ctx instanceof WriteProtectable) {
((WriteProtectable) ctx).makeReadOnly ();
}
Except you have factored out the if () test into a separate method.
The questions are now, given that the ctx instance implements
WriteProtectable:
1. Does the ctx object implement ReadOnly? It should implement
it after it had been made ReadOnly. But not before.
2. Why do I have to do a instanceof test?
> This may be part of object's contract: it still allowes modification
> of its contents after creation and then "sealing" it. Why can not
> such contract exist?
*** Because it has to be explicitely tested for. ***
> LS> If you don't know everything about the object you are
initializing,
> LS> for example, if you use an abstract factory to create the
instance,
> LS> how can you be sure that you are allowed to make it read-only?
>
> For instance because the type of the objects returned from the
> factory includes the WriteProtectable interface explicitly.
BAD:
Context ctx = makeContext();
...do stuff..
if (ctx instanceof WriteProtectable) {
((WriteProtectable) ctx).makeReadOnly ();
}
GOOD:
interface ModifiableContext extends Context {
public void makeReadOnly ();
public void put (String key, Object value);
}
ModifiableContext ctx = makeContext();
...do stuff..
ctx.makeReadOnly ();
In the BAD example, you are not sure just what you get back and have to
do typecasts and all sorts of things in client code. Just more things
that
can go wrong.
In the GOOD example, you will know, and the compiler will know, that
you can call makeReadOnly().
However, we can do one step better by applying IoC and thus *ensuring
that
makeReadOnly is called*:
BETTER:
interface ModifiableContext extends Context {
public void put (String key, Object value);
}
protected Context makeContext () {
DefaultModifiableContext mctx = new DefaultModifiableContext ();
... very basic init ...
initializeContext (mctx);
mctx.makeReadOnly(); // guaranteed to be done
return mctx;
}
protected void initializeContext (ModifiableContext mctx) {
... do stuff to mctx ...
}
Context ctx = makeContext();
Here everything is type-safe. No instanceof tests, no casting.
If you get an instance of type T then you *only* have to worry about
the T contract.
/LS
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]