[cap-talk] Singletons Considered Harmful
daw at cs.berkeley.edu
Tue Mar 30 20:01:39 PDT 2010
Raoul Duke wrote:
>with an instance variable, that variable doesn't show up in the method
(I'm going to assume you're talking about a private instance field.)
Sure it does. It shows up in the type of the receiver.
The receiver class is an abstraction of the this. The fact
that it shows up in abstracted form is a good thing: that's
what enables encapsulation.
Suppose that an object O contains private instance fields F,G,H.
Then we view F,G,H as part of the representation of O. It's none
of the business of callers of O how O chooses to represents its
state internally. Instead, callers should just think of O as one
abstract entity. The type of O is an abstract summarization of the
types of the fields of O; callers should only refer to O and O's
type, not to O.F, O.G, O.H or their types.
Now let's look at the types of the methods of O. The type of
instance methods of O includes the type of O. Thus the type of
those methods implicitly includes the instance fields (just "concealed"
or "abstracted" by the abstraction mechanism described in the previous
We wouldn't want to live in a world where the types of O.F,
O.G, O.H appeared explicitly in the externally visible types of
all methods of O, because that would violate encapsulation. The
fact that those types are implicitly fixed/specifized by the type
of the method is enough.
Let me put it another way. The web page
http://www.object-oriented-security.org/ has a bunch of
concrete arguments against singletons. Can you name one of those
which is a valid argument against instance variables? Can you spell
out that argument in concrete terms? I don't think the arguments
transpose. I think the arguments on that web page are valid
arguments against global mutable state, but they don't lead to
convincing arguments against private instance fields.
More information about the cap-talk